Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.

  • Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [8]:
import numpy as np
from glob import glob

# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 13233 total human images.
There are 8351 total dog images.

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [12]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [13]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

  • True Detected Human Faces in human_files_short: 96.0%
  • False Detected Human Faces in dog_files_short: 18.0%

I suggested a better human detection that for the same True detected human rate has less false detections when dogs are classified (see the function called human_detector_AD below):

  • True Detected Human Faces in human_files_short: 96.0%
  • False Detected Human Faces in dog_files_short: 9.0%
In [14]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
#
human_face_percentage = np.sum([1 for n in human_files_short if face_detector(n)]) * 100.0 / len(human_files_short)
dog_face_percentage   = np.sum([1 for n in dog_files_short   if face_detector(n)]) * 100.0 / len(dog_files_short)
#
print('True  Detected Human Faces in human_files_short: {0}%'.format(human_face_percentage))
print('False Detected Human Faces in   dog_files_short: {0}%'.format(dog_face_percentage))
#
True  Detected Human Faces in human_files_short: 96.0%
False Detected Human Faces in   dog_files_short: 18.0%
In [15]:
file_name_short = list(human_files_short) + list(dog_files_short)
for img_path in file_name_short:
    img = cv2.imread(img_path)
    print(img.shape)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(250, 250, 3)
(320, 314, 3)
(450, 406, 3)
(380, 300, 3)
(500, 500, 3)
(500, 375, 3)
(375, 500, 3)
(279, 264, 3)
(480, 640, 3)
(500, 484, 3)
(341, 400, 3)
(600, 450, 3)
(534, 800, 3)
(802, 626, 3)
(600, 800, 3)
(377, 270, 3)
(535, 600, 3)
(432, 358, 3)
(450, 600, 3)
(250, 200, 3)
(800, 600, 3)
(600, 450, 3)
(640, 426, 3)
(591, 640, 3)
(551, 346, 3)
(370, 470, 3)
(500, 800, 3)
(374, 250, 3)
(424, 636, 3)
(531, 800, 3)
(750, 524, 3)
(500, 334, 3)
(352, 235, 3)
(1595, 1208, 3)
(315, 400, 3)
(340, 400, 3)
(470, 300, 3)
(480, 600, 3)
(479, 499, 3)
(432, 650, 3)
(1216, 2040, 3)
(490, 550, 3)
(372, 355, 3)
(768, 1024, 3)
(291, 360, 3)
(827, 800, 3)
(500, 441, 3)
(2448, 3264, 3)
(480, 640, 3)
(480, 640, 3)
(427, 638, 3)
(425, 639, 3)
(153, 200, 3)
(639, 426, 3)
(250, 250, 3)
(638, 379, 3)
(736, 512, 3)
(400, 329, 3)
(242, 300, 3)
(380, 590, 3)
(450, 300, 3)
(360, 303, 3)
(1235, 800, 3)
(398, 300, 3)
(229, 300, 3)
(451, 300, 3)
(300, 297, 3)
(480, 640, 3)
(250, 250, 3)
(350, 262, 3)
(298, 320, 3)
(511, 270, 3)
(327, 360, 3)
(425, 635, 3)
(960, 1280, 3)
(321, 300, 3)
(599, 660, 3)
(693, 943, 3)
(233, 239, 3)
(372, 496, 3)
(343, 350, 3)
(1022, 900, 3)
(409, 300, 3)
(792, 1048, 3)
(600, 437, 3)
(325, 325, 3)
(600, 800, 3)
(1080, 1440, 3)
(253, 253, 3)
(465, 500, 3)
(749, 800, 3)
(333, 500, 3)
(500, 451, 3)
(442, 500, 3)
(450, 400, 3)
(823, 800, 3)
(495, 324, 3)
(540, 360, 3)
(375, 500, 3)
(500, 375, 3)
(365, 500, 3)

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [261]:
### (Optional) 
### TODO: Test performance of another face detection algorithm.
### Feel free to use as many code cells as needed.
### inspired by https://gilberttanner.com/blog/detectron-2-object-detection-with-pytorch
# import some common detectron2 utilities
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog
#
# Create config
cfg = get_cfg()
#cfg.merge_from_file("./detectron2_repo/configs/COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml")
cfg.merge_from_file("C:/alex/detector2/detectron2-master/configs/COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # set threshold for this model
#"COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml": "137851257/model_final_f6e8b1.pkl",
cfg.MODEL.WEIGHTS = "C:/alex/detector2/model_final_f6e8b1.pkl"
#
# Create predictor
predictor = DefaultPredictor(cfg)
#
import torch
use_cuda = torch.cuda.is_available()
#
# Make prediction
# https://github.com/facebookresearch/detectron2/issues/147
# pred_class = 0 - person, pred_class = 16 - dog 
def human_detector_AD(img_path, pred_class = 0): 
    im = cv2.imread(img_path)
    outputs = predictor(im)
    idxofClass = [i for i, x in enumerate(list(outputs['instances'].pred_classes)) if x == pred_class] # select huuman only
    if len(idxofClass) > 0:
       o = outputs["instances"]
       #classes = o.pred_classes[idxofClass]
       #boxes = o.pred_boxes[idxofClass]
       scores = o.scores[idxofClass]
       if use_cuda:
          scores = scores.cpu()
       #
       confidence = max(scores.numpy())
    else:
       confidence = 0.0
    return confidence
#
In [262]:
# PERSON DETECTOR
for threshold in np.arange(0.9, 1.0, 0.01):
    human_face_percentage = np.sum([1 for n in human_files_short if human_detector_AD(n, 0) >= threshold]) * 100.0 / len(human_files_short)
    dog_face_percentage   = np.sum([1 for n in dog_files_short   if human_detector_AD(n, 0) >= threshold]) * 100.0 / len(dog_files_short)
    #
    print("Threshold: ", threshold)
    print('True  Detected Human Faces in human_files_short: {0}%'.format(human_face_percentage))
    print('False Detected Human Faces in   dog_files_short: {0}%'.format(dog_face_percentage))
    #
Threshold:  0.9
True  Detected Human Faces in human_files_short: 99.0%
False Detected Human Faces in   dog_files_short: 14.0%
Threshold:  0.91
True  Detected Human Faces in human_files_short: 99.0%
False Detected Human Faces in   dog_files_short: 13.0%
Threshold:  0.92
True  Detected Human Faces in human_files_short: 99.0%
False Detected Human Faces in   dog_files_short: 13.0%
Threshold:  0.93
True  Detected Human Faces in human_files_short: 99.0%
False Detected Human Faces in   dog_files_short: 13.0%
Threshold:  0.9400000000000001
True  Detected Human Faces in human_files_short: 99.0%
False Detected Human Faces in   dog_files_short: 13.0%
Threshold:  0.9500000000000001
True  Detected Human Faces in human_files_short: 99.0%
False Detected Human Faces in   dog_files_short: 12.0%
Threshold:  0.9600000000000001
True  Detected Human Faces in human_files_short: 98.0%
False Detected Human Faces in   dog_files_short: 11.0%
Threshold:  0.9700000000000001
True  Detected Human Faces in human_files_short: 97.0%
False Detected Human Faces in   dog_files_short: 11.0%
Threshold:  0.9800000000000001
True  Detected Human Faces in human_files_short: 96.0%
False Detected Human Faces in   dog_files_short: 9.0%
Threshold:  0.9900000000000001
True  Detected Human Faces in human_files_short: 95.0%
False Detected Human Faces in   dog_files_short: 8.0%

Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [29]:
import torch
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()
print("use_cuda: ", use_cuda)
# move model to GPU if CUDA is available
if use_cuda:
    VGG16 = VGG16.cuda()
use_cuda:  True

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

In [30]:
from PIL import Image
import torchvision.transforms as transforms

# Set PIL to be tolerant of image files that are truncated.
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

def VGG16_predict(img_path):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    # inspired by https://gist.github.com/jkarimi91/d393688c4d4cdb9251e3f939f138876e
    # We can do all this preprocessing using a transform pipeline.
    from torch.autograd import Variable
    img = Image.open(img_path)
    min_img_size = 224  # The min size, as noted in the PyTorch pretrained models doc, is 224 px.
    transform_pipeline = transforms.Compose([transforms.Resize(min_img_size),
                                             transforms.ToTensor(),
                                             transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                                   std=[0.229, 0.224, 0.225])])
    #
    img = transform_pipeline(img)
    # Move tensor to GPU if available
    if use_cuda:
        img = img.cuda()
    #
    # PyTorch pretrained models expect the Tensor dims to be (num input imgs, num color channels, height, width).
    # Currently however, we have (num color channels, height, width); let's fix this by inserting a new axis.
    img = img.unsqueeze(0)  # Insert the new axis at index 0 i.e. in front of the other axes/dims. 
    #
    # Now that we have preprocessed our img, we need to convert it into a 
    # Variable; PyTorch models expect inputs to be Variables. A PyTorch Variable is a  
    # wrapper around a PyTorch Tensor.
    img = Variable(img)
    # Now let's load our model and get a prediciton!
    prediction = VGG16(img)  # Returns a Tensor of shape (batch, num class labels)
    #
    if use_cuda: 
       prediction = prediction.cpu() # Use Tensor.cpu() to copy the tensor to host memory first.
    #
    prediction = prediction.data.numpy().argmax()  # Our prediction will be the index of the class label with the largest value.
    return prediction # predicted class index

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [31]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    ## TODO: Complete the function.
    prediction = VGG16_predict(img_path)
    #
    if (prediction >= 151) and (prediction <= 268):
        isDog = True
    else:
        isDog = False
    return isDog # true/false

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

  • False Detected Dog Faces in human_files_short: 0.0%
  • True Detected Dog Faces in dog_files_short: 93.0%
In [32]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
#
human_face_percentage = np.sum([1 for n in human_files_short if dog_detector(n)]) * 100.0 / len(human_files_short)
dog_face_percentage   = np.sum([1 for n in dog_files_short   if dog_detector(n)]) * 100.0 / len(dog_files_short)
#
print('False  Detected Dog Faces in human_files_short: {0}%'.format(human_face_percentage))
print('True   Detected Dog Faces in   dog_files_short: {0}%'.format(dog_face_percentage))
#
False  Detected Dog Faces in human_files_short: 0.0%
True   Detected Dog Faces in   dog_files_short: 93.0%

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [253]:
### (Optional) 
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.
# DOG DETECTOR
#
#Threshold:  0.01, 0.001
#False  Detected Dog in human_files_short: 1.0%
#True   Detected Dog in dog_files_short:   93.0%
for threshold in np.arange(0.1, 0.2, 0.01): # 16 in human_detector_AD(n, 16) means we use dog detector
    human_face_percentage = np.sum([1 for n in human_files_short if human_detector_AD(n, 16) >= threshold]) * 100.0 / len(human_files_short)
    dog_face_percentage   = np.sum([1 for n in dog_files_short   if human_detector_AD(n, 16) >= threshold]) * 100.0 / len(dog_files_short)
    #
    print("Threshold: ", threshold)
    print('False  Detected Dog in human_files_short: {0}%'.format(human_face_percentage))
    print('True   Detected Dog in dog_files_short:   {0}%'.format(dog_face_percentage))
    #
Threshold:  0.1
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.11
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.12
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.13
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.13999999999999999
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.14999999999999997
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.15999999999999998
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.16999999999999998
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.17999999999999997
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%
Threshold:  0.18999999999999995
False  Detected Dog in human_files_short: 1.0%
True   Detected Dog in dog_files_short:   93.0%

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [57]:
import os
from torchvision import datasets

### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
data_dir = 'dogImages'

train_transforms = transforms.Compose([transforms.Resize(size=250),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.RandomRotation(10),
                                       transforms.CenterCrop(224),
                                       transforms.ToTensor(),
                                       transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                            std =[0.229, 0.224, 0.225])])

validTest_transforms = transforms.Compose([transforms.Resize(size=250),
                                           transforms.CenterCrop(224),
                                           transforms.ToTensor(),
                                           transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                         std=[0.229, 0.224, 0.225])])

train_dataset = datasets.ImageFolder(os.path.join(data_dir, 'train'), transform=train_transforms)
valid_dataset = datasets.ImageFolder(os.path.join(data_dir, 'valid'), transform=validTest_transforms)
test_dataset = datasets.ImageFolder(os.path.join(data_dir, 'test'), transform=validTest_transforms)

trainLoader = torch.utils.data.DataLoader(train_dataset,
                                          batch_size=64,
                                          shuffle=True,
                                          num_workers=0)

validLoader = torch.utils.data.DataLoader(valid_dataset,
                                          batch_size=64,
                                          shuffle=True,
                                          num_workers=0)

testLoader = torch.utils.data.DataLoader(test_dataset,
                                          batch_size=64,
                                          shuffle=False,
                                          num_workers=0)

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer: Because many images have size 250x250 I choose transforms.Resize(size=250). Then I perfrom image augmentation using transforms.RandomHorizontalFlip() and transforms.RandomRotation(10): image data augmentation is used to expand the training dataset in order to improve the performance and ability of the model to generalize. Then I select the centre of image using transforms.CenterCrop(224). Images can have different contrast and brightness that is why I perform transforms.Normalize.

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [52]:
import torch.nn as nn
import torch.nn.functional as F

# define the CNN architecture
class Net(nn.Module):
    ### TODO: choose an architecture, and complete the class
    def __init__(self, n_classes = 133, depth = 32):
        super(Net, self).__init__()
        ### Define layers of a CNN
        ### self.conv1 = nn.Conv2d(  3,  16, kernel_size=3, padding=1)
        ### self.conv2 = nn.Conv2d( 16,  32, kernel_size=3, padding=1)
        ### self.conv3 = nn.Conv2d( 32,  64, kernel_size=3, padding=1)
        ### self.pool = nn.MaxPool2d(2, 2)
        ### self.fc1 = nn.Linear(28 * 28 * 64, 512)
        ### self.fc2 = nn.Linear(512, 133)
        ### self.dropout = nn.Dropout(0.1)
        #
        ############################################################
        #
        scale1 = 1
        scale2 = 2
        scale3 = 4
        #
        # conv Group 1
        self.conv_Set_1_N1 = nn.Conv2d(3,              depth * scale1, 3, stride = 1, padding = 1)
        self.conv_Set_1_N2 = nn.Conv2d(depth * scale1, depth * scale1, 3, stride = 1, padding = 1)
        self.bn_Set_1_N1   = nn.BatchNorm2d(depth * scale1)
        self.bn_Set_1_N2   = nn.BatchNorm2d(depth * scale1)
        # conv Group 2
        self.conv_Set_2_N1 = nn.Conv2d(depth,          depth * scale2, 3, stride = 1, padding = 1)
        self.conv_Set_2_N2 = nn.Conv2d(depth * scale2, depth * scale2, 3, stride = 1, padding = 1)
        self.bn_Set_2_N1   = nn.BatchNorm2d(depth * scale2)
        self.bn_Set_2_N2   = nn.BatchNorm2d(depth * scale2)        
        # conv Group 3
        self.conv_Set_3_N1 = nn.Conv2d(depth * scale2, depth * scale3, 3, stride = 1, padding = 1)
        self.conv_Set_3_N2 = nn.Conv2d(depth * scale3, depth * scale3, 3, stride = 1,padding = 1)
        self.bn_Set_3_N1   = nn.BatchNorm2d(depth * scale3)
        self.bn_Set_3_N2   = nn.BatchNorm2d(depth * scale3)
        #
        self.pool = nn.MaxPool2d(2,2)
        #
        #self.out = nn.Linear(28 * 28 * depth * scale3, n_classes)
        self.fc_out = nn.Linear(depth * scale3, n_classes)   
        #
        nn.init.kaiming_normal_(self.conv_Set_1_N1.weight, nonlinearity='relu')
        nn.init.kaiming_normal_(self.conv_Set_1_N2.weight, nonlinearity='relu')
        nn.init.kaiming_normal_(self.conv_Set_2_N1.weight, nonlinearity='relu')
        nn.init.kaiming_normal_(self.conv_Set_2_N2.weight, nonlinearity='relu')
        nn.init.kaiming_normal_(self.conv_Set_3_N1.weight, nonlinearity='relu')
        nn.init.kaiming_normal_(self.conv_Set_3_N2.weight, nonlinearity='relu') 
            
        
    def forward(self, x):
        ### Define forward behavior
        ### x = self.pool(F.relu(self.conv1(x))) # 224/2 = 112 
        ### x = self.pool(F.relu(self.conv2(x))) # 112/2 = 56
        ### x = self.dropout(x)  
        ### x = self.pool(F.relu(self.conv3(x))) #  56/2 = 28
        ### x = x.view(-1, 28 * 28 * 64) # flatten image in order to used by a fully connected layer
        ### x = F.relu(self.fc1(x))
        ### x = self.dropout(x)
        ### x = self.fc2(x)
        #
        ############################################################
        #
        # conv Group 1
        x = F.relu(self.bn_Set_1_N1(self.conv_Set_1_N1(x)))
        x = F.relu(self.bn_Set_1_N2(self.conv_Set_1_N2(x)))
        x = self.pool(x) # 224/2 = 112 
        # conv Group 2
        x = F.relu(self.bn_Set_2_N1(self.conv_Set_2_N1(x)))
        x = F.relu(self.bn_Set_2_N2(self.conv_Set_2_N2(x)))
        x = self.pool(x) # 112/2 = 56
        # conv Group 3
        x = F.relu(self.bn_Set_3_N1(self.conv_Set_3_N1(x)))
        x = F.relu(self.bn_Set_3_N2(self.conv_Set_3_N2(x)))
        x = self.pool(x) #  56/2 = 28
        # First we fuse the height and width dimensions (2 and 3) 
        x = x.view(x.size(0),x.size(1),-1)        
        # And now max global pooling
        x = x.max(2)[0]
        # Output
        x = self.fc_out(x)
        return x

#-#-# You do NOT have to modify the code below this line. #-#-#

# instantiate the CNN
model_scratch = Net()

# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer: My model is inspired by VGG model- I use 3 by 3 filter for the convolutional layers and every two convolutional layers followed by pooling layer and in the end I use fully connected layer. Because of memory contrain on GPU memory and training tine I used subset of VGG layers - I use only 6 convolutional layers, 4 max pooling layers and one fully connected layer. I tried a different CNN architecture but it perfroms worse. I use convolutional layers as feature extractors and max pooling layers to add shift invariance to the model.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [53]:
import torch.optim as optim

### TODO: select loss function
criterion_scratch = nn.CrossEntropyLoss()

### TODO: select optimizer
optimizer_scratch = optim.Adam(model_scratch.parameters(), lr=  0.0011) #0.03)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [67]:
# the following import is required for training to be robust to truncated images
from PIL import ImageFile
from time import time
import pandas as pd
ImageFile.LOAD_TRUNCATED_IMAGES = True

def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    valid_loss_min = np.Inf 
    
    for epoch in range(1, n_epochs+1):
        print("epoch: ", epoch)
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        
        ###################
        # train the model #
        ###################
        model.train()
        start = time()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## find the loss and update the model parameters accordingly
            ## record the average training loss, using something like
            ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
   
            # clear gradients of all optimized variables
            optimizer.zero_grad()

            # forwarward pass
            output = model(data)
            
            # calculate batch loss
            loss = criterion(output, target)
            
            # backward pass
            loss.backward()
            
            # perform optimization step
            optimizer.step()
            
            # update training loss
            train_loss += ((1 / (batch_idx + 1)) * (loss.data - train_loss))    
            #
            if batch_idx % 50 == 0:
               end = time()
               timeAD = end-start
               print('Epoch %d, Batch %d loss: %.6f, Time %.1fs' % (epoch, batch_idx + 1, train_loss,  timeAD))
               start = end
            
        ######################    
        # validate the model #
        ######################
        model.eval()
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            #
            with torch.no_grad():
                output = model(data)
            loss = criterion(output, target)
            valid_loss += ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
            
        # print training/validation statistics 
        df = pd.DataFrame({"epoch": [epoch], "time": [timeAD], "train_loss": [train_loss], "valid_loss": [valid_loss]})
        df.to_csv("epoch_" + str(epoch) + "_accuracy.csv")
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
            epoch, 
            train_loss,
            valid_loss
            ))
        
        ## TODO: save the model if validation loss has decreased
        if valid_loss < valid_loss_min:
           print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model...'.format(valid_loss_min, valid_loss))
           torch.save(model.state_dict(), save_path)
           valid_loss_min = valid_loss           
    # return trained model
    return model

# define loaders_scratch
loaders_scratch = {'train': trainLoader,
                   'valid': validLoader,
                   'test':  testLoader}

# train the model
model_scratch = train(100, loaders_scratch, model_scratch, optimizer_scratch, 
                      criterion_scratch, use_cuda, 'model_scratch.pt')
#  test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
epoch:  1
Epoch 1, Batch 1 loss: 7.068487, Time 2.0s
Epoch 1, Batch 51 loss: 5.132473, Time 57.8s
Epoch 1, Batch 101 loss: 4.989016, Time 58.5s
Epoch: 1 	Training Loss: 4.983727 	Validation Loss: 4.752798
Validation loss decreased (inf --> 4.752798). Saving model...
epoch:  2
Epoch 2, Batch 1 loss: 4.723833, Time 0.5s
Epoch 2, Batch 51 loss: 4.715271, Time 58.8s
Epoch 2, Batch 101 loss: 4.691949, Time 58.6s
Epoch: 2 	Training Loss: 4.690682 	Validation Loss: 4.652053
Validation loss decreased (4.752798 --> 4.652053). Saving model...
epoch:  3
Epoch 3, Batch 1 loss: 4.604810, Time 0.5s
Epoch 3, Batch 51 loss: 4.552147, Time 58.6s
Epoch 3, Batch 101 loss: 4.531362, Time 58.6s
Epoch: 3 	Training Loss: 4.528723 	Validation Loss: 4.622684
Validation loss decreased (4.652053 --> 4.622684). Saving model...
epoch:  4
Epoch 4, Batch 1 loss: 4.316566, Time 0.4s
Epoch 4, Batch 51 loss: 4.424477, Time 58.4s
Epoch 4, Batch 101 loss: 4.388114, Time 58.7s
Epoch: 4 	Training Loss: 4.389485 	Validation Loss: 4.422060
Validation loss decreased (4.622684 --> 4.422060). Saving model...
epoch:  5
Epoch 5, Batch 1 loss: 4.234720, Time 0.5s
Epoch 5, Batch 51 loss: 4.268242, Time 58.7s
Epoch 5, Batch 101 loss: 4.237224, Time 58.6s
Epoch: 5 	Training Loss: 4.232965 	Validation Loss: 4.300251
Validation loss decreased (4.422060 --> 4.300251). Saving model...
epoch:  6
Epoch 6, Batch 1 loss: 3.962166, Time 0.4s
Epoch 6, Batch 51 loss: 4.098736, Time 58.7s
Epoch 6, Batch 101 loss: 4.075474, Time 58.5s
Epoch: 6 	Training Loss: 4.071764 	Validation Loss: 4.040739
Validation loss decreased (4.300251 --> 4.040739). Saving model...
epoch:  7
Epoch 7, Batch 1 loss: 3.865397, Time 0.4s
Epoch 7, Batch 51 loss: 3.903789, Time 58.4s
Epoch 7, Batch 101 loss: 3.911089, Time 58.9s
Epoch: 7 	Training Loss: 3.916349 	Validation Loss: 4.111214
epoch:  8
Epoch 8, Batch 1 loss: 3.739755, Time 0.4s
Epoch 8, Batch 51 loss: 3.762423, Time 58.6s
Epoch 8, Batch 101 loss: 3.749759, Time 58.4s
Epoch: 8 	Training Loss: 3.750885 	Validation Loss: 3.818002
Validation loss decreased (4.040739 --> 3.818002). Saving model...
epoch:  9
Epoch 9, Batch 1 loss: 3.316179, Time 0.6s
Epoch 9, Batch 51 loss: 3.594810, Time 58.7s
Epoch 9, Batch 101 loss: 3.578817, Time 58.5s
Epoch: 9 	Training Loss: 3.576357 	Validation Loss: 3.854448
epoch:  10
Epoch 10, Batch 1 loss: 3.847935, Time 0.6s
Epoch 10, Batch 51 loss: 3.454995, Time 58.4s
Epoch 10, Batch 101 loss: 3.419623, Time 58.4s
Epoch: 10 	Training Loss: 3.417073 	Validation Loss: 3.879019
epoch:  11
Epoch 11, Batch 1 loss: 3.456380, Time 0.4s
Epoch 11, Batch 51 loss: 3.309716, Time 58.7s
Epoch 11, Batch 101 loss: 3.283847, Time 58.6s
Epoch: 11 	Training Loss: 3.283820 	Validation Loss: 3.543288
Validation loss decreased (3.818002 --> 3.543288). Saving model...
epoch:  12
Epoch 12, Batch 1 loss: 3.262548, Time 0.6s
Epoch 12, Batch 51 loss: 3.173236, Time 59.1s
Epoch 12, Batch 101 loss: 3.132600, Time 58.8s
Epoch: 12 	Training Loss: 3.125885 	Validation Loss: 3.429214
Validation loss decreased (3.543288 --> 3.429214). Saving model...
epoch:  13
Epoch 13, Batch 1 loss: 3.286103, Time 0.4s
Epoch 13, Batch 51 loss: 2.993005, Time 58.5s
Epoch 13, Batch 101 loss: 2.974769, Time 58.7s
Epoch: 13 	Training Loss: 2.973976 	Validation Loss: 3.422412
Validation loss decreased (3.429214 --> 3.422412). Saving model...
epoch:  14
Epoch 14, Batch 1 loss: 2.915766, Time 0.5s
Epoch 14, Batch 51 loss: 2.888013, Time 58.5s
Epoch 14, Batch 101 loss: 2.859061, Time 58.6s
Epoch: 14 	Training Loss: 2.855298 	Validation Loss: 3.242649
Validation loss decreased (3.422412 --> 3.242649). Saving model...
epoch:  15
Epoch 15, Batch 1 loss: 2.357158, Time 0.7s
Epoch 15, Batch 51 loss: 2.740228, Time 58.4s
Epoch 15, Batch 101 loss: 2.710264, Time 58.6s
Epoch: 15 	Training Loss: 2.715827 	Validation Loss: 3.010715
Validation loss decreased (3.242649 --> 3.010715). Saving model...
epoch:  16
Epoch 16, Batch 1 loss: 2.374027, Time 0.4s
Epoch 16, Batch 51 loss: 2.546295, Time 58.4s
Epoch 16, Batch 101 loss: 2.553808, Time 58.6s
Epoch: 16 	Training Loss: 2.553897 	Validation Loss: 3.260051
epoch:  17
Epoch 17, Batch 1 loss: 2.480173, Time 0.4s
Epoch 17, Batch 51 loss: 2.459254, Time 58.6s
Epoch 17, Batch 101 loss: 2.463836, Time 58.6s
Epoch: 17 	Training Loss: 2.457944 	Validation Loss: 2.885220
Validation loss decreased (3.010715 --> 2.885220). Saving model...
epoch:  18
Epoch 18, Batch 1 loss: 2.370598, Time 0.6s
Epoch 18, Batch 51 loss: 2.313555, Time 58.6s
Epoch 18, Batch 101 loss: 2.316781, Time 58.5s
Epoch: 18 	Training Loss: 2.324075 	Validation Loss: 3.061124
epoch:  19
Epoch 19, Batch 1 loss: 2.329475, Time 0.5s
Epoch 19, Batch 51 loss: 2.224949, Time 58.3s
Epoch 19, Batch 101 loss: 2.224957, Time 58.6s
Epoch: 19 	Training Loss: 2.223166 	Validation Loss: 2.801345
Validation loss decreased (2.885220 --> 2.801345). Saving model...
epoch:  20
Epoch 20, Batch 1 loss: 1.700854, Time 0.6s
Epoch 20, Batch 51 loss: 2.131651, Time 58.4s
Epoch 20, Batch 101 loss: 2.116100, Time 58.7s
Epoch: 20 	Training Loss: 2.119623 	Validation Loss: 2.727840
Validation loss decreased (2.801345 --> 2.727840). Saving model...
epoch:  21
Epoch 21, Batch 1 loss: 1.892565, Time 0.5s
Epoch 21, Batch 51 loss: 1.952461, Time 58.4s
Epoch 21, Batch 101 loss: 2.003305, Time 58.6s
Epoch: 21 	Training Loss: 2.004417 	Validation Loss: 2.675611
Validation loss decreased (2.727840 --> 2.675611). Saving model...
epoch:  22
Epoch 22, Batch 1 loss: 1.706741, Time 0.4s
Epoch 22, Batch 51 loss: 1.932140, Time 58.6s
Epoch 22, Batch 101 loss: 1.941824, Time 58.4s
Epoch: 22 	Training Loss: 1.946354 	Validation Loss: 2.624904
Validation loss decreased (2.675611 --> 2.624904). Saving model...
epoch:  23
Epoch 23, Batch 1 loss: 1.673824, Time 0.5s
Epoch 23, Batch 51 loss: 1.870053, Time 58.6s
Epoch 23, Batch 101 loss: 1.838142, Time 58.7s
Epoch: 23 	Training Loss: 1.846510 	Validation Loss: 2.650150
epoch:  24
Epoch 24, Batch 1 loss: 1.824965, Time 0.4s
Epoch 24, Batch 51 loss: 1.758273, Time 58.5s
Epoch 24, Batch 101 loss: 1.772511, Time 58.4s
Epoch: 24 	Training Loss: 1.769384 	Validation Loss: 2.369006
Validation loss decreased (2.624904 --> 2.369006). Saving model...
epoch:  25
Epoch 25, Batch 1 loss: 1.769814, Time 0.4s
Epoch 25, Batch 51 loss: 1.651669, Time 58.6s
Epoch 25, Batch 101 loss: 1.689337, Time 58.5s
Epoch: 25 	Training Loss: 1.687287 	Validation Loss: 2.567296
epoch:  26
Epoch 26, Batch 1 loss: 1.560403, Time 0.5s
Epoch 26, Batch 51 loss: 1.576327, Time 58.8s
Epoch 26, Batch 101 loss: 1.594828, Time 58.6s
Epoch: 26 	Training Loss: 1.594622 	Validation Loss: 2.472809
epoch:  27
Epoch 27, Batch 1 loss: 1.686749, Time 0.4s
Epoch 27, Batch 51 loss: 1.517521, Time 58.6s
Epoch 27, Batch 101 loss: 1.558056, Time 58.4s
Epoch: 27 	Training Loss: 1.562607 	Validation Loss: 2.534303
epoch:  28
Epoch 28, Batch 1 loss: 1.271556, Time 0.4s
Epoch 28, Batch 51 loss: 1.464526, Time 58.5s
Epoch 28, Batch 101 loss: 1.470356, Time 58.7s
Epoch: 28 	Training Loss: 1.472247 	Validation Loss: 2.463580
epoch:  29
Epoch 29, Batch 1 loss: 1.482676, Time 0.6s
Epoch 29, Batch 51 loss: 1.352425, Time 58.5s
Epoch 29, Batch 101 loss: 1.388770, Time 58.6s
Epoch: 29 	Training Loss: 1.389610 	Validation Loss: 2.318804
Validation loss decreased (2.369006 --> 2.318804). Saving model...
epoch:  30
Epoch 30, Batch 1 loss: 1.377467, Time 0.9s
Epoch 30, Batch 51 loss: 1.315641, Time 58.6s
Epoch 30, Batch 101 loss: 1.321314, Time 58.5s
Epoch: 30 	Training Loss: 1.328710 	Validation Loss: 2.284645
Validation loss decreased (2.318804 --> 2.284645). Saving model...
epoch:  31
Epoch 31, Batch 1 loss: 1.361419, Time 0.4s
Epoch 31, Batch 51 loss: 1.317728, Time 58.6s
Epoch 31, Batch 101 loss: 1.305676, Time 58.4s
Epoch: 31 	Training Loss: 1.298016 	Validation Loss: 2.373986
epoch:  32
Epoch 32, Batch 1 loss: 1.539664, Time 0.5s
Epoch 32, Batch 51 loss: 1.255117, Time 58.5s
Epoch 32, Batch 101 loss: 1.229737, Time 58.4s
Epoch: 32 	Training Loss: 1.231118 	Validation Loss: 2.463247
epoch:  33
Epoch 33, Batch 1 loss: 0.900351, Time 0.4s
Epoch 33, Batch 51 loss: 1.157760, Time 58.4s
Epoch 33, Batch 101 loss: 1.186367, Time 58.6s
Epoch: 33 	Training Loss: 1.187983 	Validation Loss: 2.214195
Validation loss decreased (2.284645 --> 2.214195). Saving model...
epoch:  34
Epoch 34, Batch 1 loss: 1.134170, Time 0.5s
Epoch 34, Batch 51 loss: 1.123278, Time 58.7s
Epoch 34, Batch 101 loss: 1.132738, Time 58.6s
Epoch: 34 	Training Loss: 1.129151 	Validation Loss: 2.315051
epoch:  35
Epoch 35, Batch 1 loss: 0.899525, Time 0.7s
Epoch 35, Batch 51 loss: 1.079259, Time 58.5s
Epoch 35, Batch 101 loss: 1.093502, Time 58.4s
Epoch: 35 	Training Loss: 1.093555 	Validation Loss: 2.124367
Validation loss decreased (2.214195 --> 2.124367). Saving model...
epoch:  36
Epoch 36, Batch 1 loss: 1.041941, Time 0.4s
Epoch 36, Batch 51 loss: 1.066239, Time 58.5s
Epoch 36, Batch 101 loss: 1.050123, Time 58.2s
Epoch: 36 	Training Loss: 1.057101 	Validation Loss: 2.483678
epoch:  37
Epoch 37, Batch 1 loss: 1.295803, Time 0.4s
Epoch 37, Batch 51 loss: 1.011032, Time 58.6s
Epoch 37, Batch 101 loss: 1.022914, Time 58.4s
Epoch: 37 	Training Loss: 1.024320 	Validation Loss: 2.263089
epoch:  38
Epoch 38, Batch 1 loss: 1.022731, Time 0.4s
Epoch 38, Batch 51 loss: 0.983253, Time 58.3s
Epoch 38, Batch 101 loss: 0.974154, Time 58.6s
Epoch: 38 	Training Loss: 0.968465 	Validation Loss: 2.206608
epoch:  39
Epoch 39, Batch 1 loss: 0.830116, Time 0.6s
Epoch 39, Batch 51 loss: 0.913162, Time 58.4s
Epoch 39, Batch 101 loss: 0.941361, Time 58.4s
Epoch: 39 	Training Loss: 0.941910 	Validation Loss: 2.294847
epoch:  40
Epoch 40, Batch 1 loss: 0.875257, Time 0.6s
Epoch 40, Batch 51 loss: 0.885718, Time 58.4s
Epoch 40, Batch 101 loss: 0.902623, Time 58.4s
Epoch: 40 	Training Loss: 0.903927 	Validation Loss: 2.183544
epoch:  41
Epoch 41, Batch 1 loss: 0.803778, Time 0.5s
Epoch 41, Batch 51 loss: 0.839659, Time 58.5s
Epoch 41, Batch 101 loss: 0.868230, Time 58.4s
Epoch: 41 	Training Loss: 0.875623 	Validation Loss: 2.282640
epoch:  42
Epoch 42, Batch 1 loss: 1.056580, Time 0.4s
Epoch 42, Batch 51 loss: 0.827838, Time 58.3s
Epoch 42, Batch 101 loss: 0.839392, Time 58.3s
Epoch: 42 	Training Loss: 0.842564 	Validation Loss: 2.209351
epoch:  43
Epoch 43, Batch 1 loss: 0.695385, Time 0.5s
Epoch 43, Batch 51 loss: 0.755531, Time 58.6s
Epoch 43, Batch 101 loss: 0.803319, Time 58.5s
Epoch: 43 	Training Loss: 0.805948 	Validation Loss: 2.164677
epoch:  44
Epoch 44, Batch 1 loss: 0.658924, Time 0.5s
Epoch 44, Batch 51 loss: 0.736271, Time 58.4s
Epoch 44, Batch 101 loss: 0.762666, Time 58.5s
Epoch: 44 	Training Loss: 0.765345 	Validation Loss: 2.077804
Validation loss decreased (2.124367 --> 2.077804). Saving model...
epoch:  45
Epoch 45, Batch 1 loss: 0.789734, Time 0.4s
Epoch 45, Batch 51 loss: 0.754577, Time 58.3s
Epoch 45, Batch 101 loss: 0.768165, Time 58.4s
Epoch: 45 	Training Loss: 0.768293 	Validation Loss: 2.554394
epoch:  46
Epoch 46, Batch 1 loss: 0.829813, Time 0.5s
Epoch 46, Batch 51 loss: 0.717007, Time 58.4s
Epoch 46, Batch 101 loss: 0.726400, Time 58.3s
Epoch: 46 	Training Loss: 0.725997 	Validation Loss: 2.306122
epoch:  47
Epoch 47, Batch 1 loss: 0.527808, Time 0.4s
Epoch 47, Batch 51 loss: 0.655977, Time 58.3s
Epoch 47, Batch 101 loss: 0.673193, Time 58.5s
Epoch: 47 	Training Loss: 0.679758 	Validation Loss: 2.227925
epoch:  48
Epoch 48, Batch 1 loss: 0.696199, Time 0.5s
Epoch 48, Batch 51 loss: 0.659898, Time 58.6s
Epoch 48, Batch 101 loss: 0.675952, Time 58.6s
Epoch: 48 	Training Loss: 0.675690 	Validation Loss: 2.250697
epoch:  49
Epoch 49, Batch 1 loss: 0.518505, Time 0.5s
Epoch 49, Batch 51 loss: 0.605626, Time 58.4s
Epoch 49, Batch 101 loss: 0.623390, Time 58.7s
Epoch: 49 	Training Loss: 0.625181 	Validation Loss: 2.205161
epoch:  50
Epoch 50, Batch 1 loss: 0.528443, Time 0.6s
Epoch 50, Batch 51 loss: 0.642418, Time 58.5s
Epoch 50, Batch 101 loss: 0.626749, Time 58.3s
Epoch: 50 	Training Loss: 0.626911 	Validation Loss: 2.402214
epoch:  51
Epoch 51, Batch 1 loss: 0.617390, Time 0.5s
Epoch 51, Batch 51 loss: 0.567991, Time 58.6s
Epoch 51, Batch 101 loss: 0.590174, Time 58.5s
Epoch: 51 	Training Loss: 0.591847 	Validation Loss: 2.142514
epoch:  52
Epoch 52, Batch 1 loss: 0.261217, Time 0.5s
Epoch 52, Batch 51 loss: 0.546122, Time 58.5s
Epoch 52, Batch 101 loss: 0.574863, Time 58.4s
Epoch: 52 	Training Loss: 0.581175 	Validation Loss: 2.499272
epoch:  53
Epoch 53, Batch 1 loss: 0.655705, Time 0.4s
Epoch 53, Batch 51 loss: 0.545821, Time 58.7s
Epoch 53, Batch 101 loss: 0.556117, Time 58.5s
Epoch: 53 	Training Loss: 0.557341 	Validation Loss: 2.283721
epoch:  54
Epoch 54, Batch 1 loss: 0.545339, Time 0.4s
Epoch 54, Batch 51 loss: 0.525774, Time 58.7s
Epoch 54, Batch 101 loss: 0.543896, Time 58.5s
Epoch: 54 	Training Loss: 0.547431 	Validation Loss: 2.217489
epoch:  55
Epoch 55, Batch 1 loss: 0.606006, Time 0.5s
Epoch 55, Batch 51 loss: 0.521088, Time 58.4s
Epoch 55, Batch 101 loss: 0.535343, Time 58.6s
Epoch: 55 	Training Loss: 0.538961 	Validation Loss: 2.261276
epoch:  56
Epoch 56, Batch 1 loss: 0.545973, Time 0.5s
Epoch 56, Batch 51 loss: 0.511156, Time 58.2s
Epoch 56, Batch 101 loss: 0.520487, Time 58.6s
Epoch: 56 	Training Loss: 0.526245 	Validation Loss: 2.237473
epoch:  57
Epoch 57, Batch 1 loss: 0.413505, Time 0.5s
Epoch 57, Batch 51 loss: 0.456680, Time 58.4s
Epoch 57, Batch 101 loss: 0.482327, Time 58.5s
Epoch: 57 	Training Loss: 0.483719 	Validation Loss: 2.133392
epoch:  58
Epoch 58, Batch 1 loss: 0.269187, Time 0.4s
Epoch 58, Batch 51 loss: 0.488146, Time 58.4s
Epoch 58, Batch 101 loss: 0.475967, Time 58.5s
Epoch: 58 	Training Loss: 0.476784 	Validation Loss: 2.267144
epoch:  59
Epoch 59, Batch 1 loss: 0.362559, Time 0.4s
Epoch 59, Batch 51 loss: 0.398935, Time 58.5s
Epoch 59, Batch 101 loss: 0.424691, Time 58.4s
Epoch: 59 	Training Loss: 0.426538 	Validation Loss: 2.129229
epoch:  60
Epoch 60, Batch 1 loss: 0.277734, Time 0.5s
Epoch 60, Batch 51 loss: 0.404996, Time 58.5s
Epoch 60, Batch 101 loss: 0.437852, Time 58.5s
Epoch: 60 	Training Loss: 0.439054 	Validation Loss: 2.330358
epoch:  61
Epoch 61, Batch 1 loss: 0.401383, Time 0.4s
Epoch 61, Batch 51 loss: 0.411329, Time 58.6s
Epoch 61, Batch 101 loss: 0.425776, Time 58.5s
Epoch: 61 	Training Loss: 0.427091 	Validation Loss: 2.211761
epoch:  62
Epoch 62, Batch 1 loss: 0.339298, Time 0.4s
Epoch 62, Batch 51 loss: 0.395658, Time 58.3s
Epoch 62, Batch 101 loss: 0.393151, Time 58.5s
Epoch: 62 	Training Loss: 0.392577 	Validation Loss: 2.459107
epoch:  63
Epoch 63, Batch 1 loss: 0.245453, Time 0.5s
Epoch 63, Batch 51 loss: 0.379946, Time 58.4s
Epoch 63, Batch 101 loss: 0.397787, Time 58.4s
Epoch: 63 	Training Loss: 0.399158 	Validation Loss: 2.302577
epoch:  64
Epoch 64, Batch 1 loss: 0.317512, Time 0.5s
Epoch 64, Batch 51 loss: 0.360642, Time 58.5s
Epoch 64, Batch 101 loss: 0.379028, Time 58.4s
Epoch: 64 	Training Loss: 0.375183 	Validation Loss: 2.346473
epoch:  65
Epoch 65, Batch 1 loss: 0.418435, Time 0.6s
Epoch 65, Batch 51 loss: 0.373223, Time 58.4s
Epoch 65, Batch 101 loss: 0.401667, Time 58.4s
Epoch: 65 	Training Loss: 0.400512 	Validation Loss: 2.802507
epoch:  66
Epoch 66, Batch 1 loss: 0.341958, Time 0.6s
Epoch 66, Batch 51 loss: 0.353547, Time 58.4s
Epoch 66, Batch 101 loss: 0.372255, Time 58.7s
Epoch: 66 	Training Loss: 0.373282 	Validation Loss: 2.262009
epoch:  67
Epoch 67, Batch 1 loss: 0.335294, Time 0.6s
Epoch 67, Batch 51 loss: 0.325613, Time 58.5s
Epoch 67, Batch 101 loss: 0.333188, Time 58.4s
Epoch: 67 	Training Loss: 0.335851 	Validation Loss: 2.359192
epoch:  68
Epoch 68, Batch 1 loss: 0.207217, Time 0.4s
Epoch 68, Batch 51 loss: 0.325279, Time 58.5s
Epoch 68, Batch 101 loss: 0.339100, Time 58.6s
Epoch: 68 	Training Loss: 0.338690 	Validation Loss: 2.300637
epoch:  69
Epoch 69, Batch 1 loss: 0.280580, Time 0.4s
Epoch 69, Batch 51 loss: 0.348317, Time 58.4s
Epoch 69, Batch 101 loss: 0.361339, Time 58.3s
Epoch: 69 	Training Loss: 0.360804 	Validation Loss: 2.290102
epoch:  70
Epoch 70, Batch 1 loss: 0.376333, Time 0.5s
Epoch 70, Batch 51 loss: 0.322888, Time 58.5s
Epoch 70, Batch 101 loss: 0.319145, Time 58.3s
Epoch: 70 	Training Loss: 0.320473 	Validation Loss: 2.238481
epoch:  71
Epoch 71, Batch 1 loss: 0.251734, Time 0.5s
Epoch 71, Batch 51 loss: 0.310126, Time 58.6s
Epoch 71, Batch 101 loss: 0.324195, Time 58.6s
Epoch: 71 	Training Loss: 0.327370 	Validation Loss: 2.521839
epoch:  72
Epoch 72, Batch 1 loss: 0.212154, Time 0.4s
Epoch 72, Batch 51 loss: 0.336456, Time 58.7s
Epoch 72, Batch 101 loss: 0.335036, Time 58.6s
Epoch: 72 	Training Loss: 0.336208 	Validation Loss: 2.536568
epoch:  73
Epoch 73, Batch 1 loss: 0.207947, Time 0.5s
Epoch 73, Batch 51 loss: 0.334855, Time 58.5s
Epoch 73, Batch 101 loss: 0.319567, Time 58.5s
Epoch: 73 	Training Loss: 0.317866 	Validation Loss: 2.538378
epoch:  74
Epoch 74, Batch 1 loss: 0.381587, Time 0.4s
Epoch 74, Batch 51 loss: 0.309521, Time 58.4s
Epoch 74, Batch 101 loss: 0.298006, Time 58.4s
Epoch: 74 	Training Loss: 0.295695 	Validation Loss: 2.421778
epoch:  75
Epoch 75, Batch 1 loss: 0.226329, Time 0.6s
Epoch 75, Batch 51 loss: 0.265085, Time 58.4s
Epoch 75, Batch 101 loss: 0.276802, Time 58.6s
Epoch: 75 	Training Loss: 0.278679 	Validation Loss: 2.447450
epoch:  76
Epoch 76, Batch 1 loss: 0.173500, Time 0.4s
Epoch 76, Batch 51 loss: 0.246761, Time 58.3s
Epoch 76, Batch 101 loss: 0.269957, Time 58.5s
Epoch: 76 	Training Loss: 0.269073 	Validation Loss: 2.426606
epoch:  77
Epoch 77, Batch 1 loss: 0.194616, Time 0.5s
Epoch 77, Batch 51 loss: 0.256476, Time 58.3s
Epoch 77, Batch 101 loss: 0.280704, Time 58.4s
Epoch: 77 	Training Loss: 0.282426 	Validation Loss: 2.423526
epoch:  78
Epoch 78, Batch 1 loss: 0.493809, Time 0.4s
Epoch 78, Batch 51 loss: 0.302204, Time 58.5s
Epoch 78, Batch 101 loss: 0.302980, Time 58.7s
Epoch: 78 	Training Loss: 0.301501 	Validation Loss: 2.641927
epoch:  79
Epoch 79, Batch 1 loss: 0.371460, Time 0.5s
Epoch 79, Batch 51 loss: 0.277403, Time 58.6s
Epoch 79, Batch 101 loss: 0.270603, Time 58.5s
Epoch: 79 	Training Loss: 0.273833 	Validation Loss: 2.530507
epoch:  80
Epoch 80, Batch 1 loss: 0.182709, Time 0.7s
Epoch 80, Batch 51 loss: 0.267536, Time 58.5s
Epoch 80, Batch 101 loss: 0.268416, Time 58.5s
Epoch: 80 	Training Loss: 0.271380 	Validation Loss: 2.439457
epoch:  81
Epoch 81, Batch 1 loss: 0.476235, Time 0.6s
Epoch 81, Batch 51 loss: 0.285912, Time 58.3s
Epoch 81, Batch 101 loss: 0.282970, Time 58.3s
Epoch: 81 	Training Loss: 0.283439 	Validation Loss: 2.618315
epoch:  82
Epoch 82, Batch 1 loss: 0.315328, Time 0.4s
Epoch 82, Batch 51 loss: 0.264728, Time 58.7s
Epoch 82, Batch 101 loss: 0.262282, Time 58.4s
Epoch: 82 	Training Loss: 0.262527 	Validation Loss: 2.362098
epoch:  83
Epoch 83, Batch 1 loss: 0.112654, Time 0.5s
Epoch 83, Batch 51 loss: 0.246108, Time 58.4s
Epoch 83, Batch 101 loss: 0.241705, Time 58.6s
Epoch: 83 	Training Loss: 0.242343 	Validation Loss: 2.609907
epoch:  84
Epoch 84, Batch 1 loss: 0.267139, Time 0.6s
Epoch 84, Batch 51 loss: 0.234476, Time 58.4s
Epoch 84, Batch 101 loss: 0.233808, Time 58.3s
Epoch: 84 	Training Loss: 0.234497 	Validation Loss: 2.622372
epoch:  85
Epoch 85, Batch 1 loss: 0.218818, Time 0.3s
Epoch 85, Batch 51 loss: 0.256897, Time 58.4s
Epoch 85, Batch 101 loss: 0.254702, Time 58.5s
Epoch: 85 	Training Loss: 0.253561 	Validation Loss: 2.335601
epoch:  86
Epoch 86, Batch 1 loss: 0.219419, Time 0.4s
Epoch 86, Batch 51 loss: 0.225424, Time 58.6s
Epoch 86, Batch 101 loss: 0.235504, Time 58.4s
Epoch: 86 	Training Loss: 0.241386 	Validation Loss: 2.440089
epoch:  87
Epoch 87, Batch 1 loss: 0.091673, Time 0.5s
Epoch 87, Batch 51 loss: 0.281860, Time 58.6s
Epoch 87, Batch 101 loss: 0.268693, Time 58.6s
Epoch: 87 	Training Loss: 0.269404 	Validation Loss: 2.337200
epoch:  88
Epoch 88, Batch 1 loss: 0.249881, Time 0.4s
Epoch 88, Batch 51 loss: 0.231367, Time 58.6s
Epoch 88, Batch 101 loss: 0.255154, Time 58.5s
Epoch: 88 	Training Loss: 0.255287 	Validation Loss: 2.660615
epoch:  89
Epoch 89, Batch 1 loss: 0.195260, Time 0.5s
Epoch 89, Batch 51 loss: 0.209858, Time 58.3s
Epoch 89, Batch 101 loss: 0.213503, Time 58.6s
Epoch: 89 	Training Loss: 0.214683 	Validation Loss: 2.630742
epoch:  90
Epoch 90, Batch 1 loss: 0.122631, Time 0.5s
Epoch 90, Batch 51 loss: 0.217916, Time 58.5s
Epoch 90, Batch 101 loss: 0.224591, Time 58.3s
Epoch: 90 	Training Loss: 0.224563 	Validation Loss: 2.694303
epoch:  91
Epoch 91, Batch 1 loss: 0.184248, Time 0.4s
Epoch 91, Batch 51 loss: 0.215895, Time 58.5s
Epoch 91, Batch 101 loss: 0.233254, Time 58.5s
Epoch: 91 	Training Loss: 0.232742 	Validation Loss: 2.674988
epoch:  92
Epoch 92, Batch 1 loss: 0.257882, Time 0.5s
Epoch 92, Batch 51 loss: 0.207797, Time 58.4s
Epoch 92, Batch 101 loss: 0.203695, Time 58.3s
Epoch: 92 	Training Loss: 0.206610 	Validation Loss: 2.842435
epoch:  93
Epoch 93, Batch 1 loss: 0.291948, Time 0.4s
Epoch 93, Batch 51 loss: 0.229376, Time 58.3s
Epoch 93, Batch 101 loss: 0.219285, Time 58.5s
Epoch: 93 	Training Loss: 0.219541 	Validation Loss: 2.921709
epoch:  94
Epoch 94, Batch 1 loss: 0.199544, Time 0.5s
Epoch 94, Batch 51 loss: 0.203264, Time 58.6s
Epoch 94, Batch 101 loss: 0.205906, Time 58.5s
Epoch: 94 	Training Loss: 0.209632 	Validation Loss: 2.463331
epoch:  95
Epoch 95, Batch 1 loss: 0.095306, Time 0.4s
Epoch 95, Batch 51 loss: 0.212254, Time 58.3s
Epoch 95, Batch 101 loss: 0.211616, Time 58.8s
Epoch: 95 	Training Loss: 0.208626 	Validation Loss: 2.506513
epoch:  96
Epoch 96, Batch 1 loss: 0.142526, Time 0.6s
Epoch 96, Batch 51 loss: 0.193602, Time 58.4s
Epoch 96, Batch 101 loss: 0.203378, Time 58.7s
Epoch: 96 	Training Loss: 0.203315 	Validation Loss: 2.590980
epoch:  97
Epoch 97, Batch 1 loss: 0.200581, Time 0.5s
Epoch 97, Batch 51 loss: 0.178461, Time 58.6s
Epoch 97, Batch 101 loss: 0.179727, Time 58.6s
Epoch: 97 	Training Loss: 0.178483 	Validation Loss: 2.720165
epoch:  98
Epoch 98, Batch 1 loss: 0.220036, Time 0.5s
Epoch 98, Batch 51 loss: 0.165293, Time 58.6s
Epoch 98, Batch 101 loss: 0.164658, Time 58.5s
Epoch: 98 	Training Loss: 0.165819 	Validation Loss: 2.555055
epoch:  99
Epoch 99, Batch 1 loss: 0.150004, Time 0.4s
Epoch 99, Batch 51 loss: 0.181867, Time 58.4s
Epoch 99, Batch 101 loss: 0.172955, Time 58.7s
Epoch: 99 	Training Loss: 0.173760 	Validation Loss: 2.670139
epoch:  100
Epoch 100, Batch 1 loss: 0.117285, Time 0.4s
Epoch 100, Batch 51 loss: 0.186906, Time 58.5s
Epoch 100, Batch 101 loss: 0.185709, Time 58.5s
Epoch: 100 	Training Loss: 0.185794 	Validation Loss: 2.509060
Out[67]:
<All keys matched successfully>
In [68]:
# setting device on GPU if available, else CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()

#Additional Info when using cuda
if device.type == 'cuda':
    print(torch.cuda.get_device_name(0))
    print('Memory Usage:')
    print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
    print('Cached:   ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')
Using device: cuda

GeForce GTX 1080 Ti
Memory Usage:
Allocated: 0.8 GB
Cached:    6.0 GB
In [69]:
if use_cuda:
   torch.cuda.empty_cache()
In [70]:
# setting device on GPU if available, else CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()

#Additional Info when using cuda
if device.type == 'cuda':
    print(torch.cuda.get_device_name(0))
    print('Memory Usage:')
    print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
    print('Cached:   ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')
Using device: cuda

GeForce GTX 1080 Ti
Memory Usage:
Allocated: 0.8 GB
Cached:    1.3 GB

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [251]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        #
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        #
        #aad = data.cpu().size()
        #print("Tensor size: ", aad)
        #print("output: ", output.cpu().size())
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))

# call test function    
# load the model that got the best validation accuracy
dev = "cpu"
model_scratch_cpu = model_scratch.to(dev)   #does not have much memory on GPU
test(loaders_scratch, model_scratch_cpu, criterion_scratch, use_cuda = False) 
Test Loss: 2.149894


Test Accuracy: 43% (362/836)

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [72]:
## TODO: Specify data loaders
loaders_transfer = {'train': trainLoader,
                    'valid': validLoader,
                    'test':  testLoader}

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [246]:
import torchvision.models as models
import torch.nn as nn

## TODO: Specify model architecture 
n_classes = 133
model_transfer = models.resnet50(pretrained=True)
# Freezing all parameters
for param in model_transfer.parameters():
    param.requires_grad = False
#
# Replacing the last layer (by default it will have requires_grad == True)
model_transfer.fc = nn.Linear(model_transfer.fc.in_features,n_classes)
# Initialize the weights of the new layer
#######nn.init.kaiming_normal_(model_transfer.fc.weight, nonlinearity='relu')
#
if use_cuda:
    model_transfer = model_transfer.cuda()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: Resnet is a interesting CNN that has residual connections that allow it to be deeper than previous architectures and provide very promising results for different datasets. We use pre-trained Resnet as feature extrator. For transfer learning, I replace the final linear layer. I checked performance of the model with/wo nn.init.kaimingnormal it is not significantly better when we use nn.init.kaimingnormal.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [247]:
criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = optim.Adam(model_transfer.parameters(),3e-4) 

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [248]:
# train the model
n_epochs = 100
model_transfer =  train(n_epochs, loaders_transfer, model_transfer, 
                        optimizer_transfer, criterion_transfer, 
                        use_cuda, 'model_transfer.pt')

# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
epoch:  1
Epoch 1, Batch 1 loss: 4.958415, Time 0.4s
Epoch 1, Batch 51 loss: 4.239339, Time 25.1s
Epoch 1, Batch 101 loss: 3.558372, Time 24.3s
Epoch: 1 	Training Loss: 3.515169 	Validation Loss: 2.203759
Validation loss decreased (inf --> 2.203759). Saving model...
epoch:  2
Epoch 2, Batch 1 loss: 2.069845, Time 0.6s
Epoch 2, Batch 51 loss: 1.898240, Time 24.1s
Epoch 2, Batch 101 loss: 1.670875, Time 25.6s
Epoch: 2 	Training Loss: 1.660126 	Validation Loss: 1.232461
Validation loss decreased (2.203759 --> 1.232461). Saving model...
epoch:  3
Epoch 3, Batch 1 loss: 1.323029, Time 0.4s
Epoch 3, Batch 51 loss: 1.138325, Time 24.9s
Epoch 3, Batch 101 loss: 1.054424, Time 24.9s
Epoch: 3 	Training Loss: 1.047139 	Validation Loss: 0.898189
Validation loss decreased (1.232461 --> 0.898189). Saving model...
epoch:  4
Epoch 4, Batch 1 loss: 0.738807, Time 0.7s
Epoch 4, Batch 51 loss: 0.837661, Time 24.7s
Epoch 4, Batch 101 loss: 0.789979, Time 25.1s
Epoch: 4 	Training Loss: 0.784977 	Validation Loss: 0.811452
Validation loss decreased (0.898189 --> 0.811452). Saving model...
epoch:  5
Epoch 5, Batch 1 loss: 0.845056, Time 0.5s
Epoch 5, Batch 51 loss: 0.670342, Time 24.4s
Epoch 5, Batch 101 loss: 0.642444, Time 25.1s
Epoch: 5 	Training Loss: 0.646203 	Validation Loss: 0.677136
Validation loss decreased (0.811452 --> 0.677136). Saving model...
epoch:  6
Epoch 6, Batch 1 loss: 0.577744, Time 0.5s
Epoch 6, Batch 51 loss: 0.533800, Time 24.7s
Epoch 6, Batch 101 loss: 0.539639, Time 24.9s
Epoch: 6 	Training Loss: 0.540585 	Validation Loss: 0.569284
Validation loss decreased (0.677136 --> 0.569284). Saving model...
epoch:  7
Epoch 7, Batch 1 loss: 0.521371, Time 0.5s
Epoch 7, Batch 51 loss: 0.487629, Time 24.1s
Epoch 7, Batch 101 loss: 0.482662, Time 25.5s
Epoch: 7 	Training Loss: 0.484026 	Validation Loss: 0.538357
Validation loss decreased (0.569284 --> 0.538357). Saving model...
epoch:  8
Epoch 8, Batch 1 loss: 0.506525, Time 0.5s
Epoch 8, Batch 51 loss: 0.450374, Time 25.0s
Epoch 8, Batch 101 loss: 0.434673, Time 24.8s
Epoch: 8 	Training Loss: 0.434041 	Validation Loss: 0.534129
Validation loss decreased (0.538357 --> 0.534129). Saving model...
epoch:  9
Epoch 9, Batch 1 loss: 0.345552, Time 0.4s
Epoch 9, Batch 51 loss: 0.399072, Time 24.7s
Epoch 9, Batch 101 loss: 0.393398, Time 24.9s
Epoch: 9 	Training Loss: 0.396393 	Validation Loss: 0.515887
Validation loss decreased (0.534129 --> 0.515887). Saving model...
epoch:  10
Epoch 10, Batch 1 loss: 0.468783, Time 0.5s
Epoch 10, Batch 51 loss: 0.360169, Time 25.0s
Epoch 10, Batch 101 loss: 0.361847, Time 24.9s
Epoch: 10 	Training Loss: 0.360674 	Validation Loss: 0.487590
Validation loss decreased (0.515887 --> 0.487590). Saving model...
epoch:  11
Epoch 11, Batch 1 loss: 0.372312, Time 0.5s
Epoch 11, Batch 51 loss: 0.328648, Time 24.4s
Epoch 11, Batch 101 loss: 0.336437, Time 25.9s
Epoch: 11 	Training Loss: 0.341831 	Validation Loss: 0.490226
epoch:  12
Epoch 12, Batch 1 loss: 0.274671, Time 0.5s
Epoch 12, Batch 51 loss: 0.309203, Time 26.0s
Epoch 12, Batch 101 loss: 0.307177, Time 24.8s
Epoch: 12 	Training Loss: 0.306074 	Validation Loss: 0.471793
Validation loss decreased (0.487590 --> 0.471793). Saving model...
epoch:  13
Epoch 13, Batch 1 loss: 0.334329, Time 0.4s
Epoch 13, Batch 51 loss: 0.297148, Time 25.0s
Epoch 13, Batch 101 loss: 0.291188, Time 25.3s
Epoch: 13 	Training Loss: 0.291078 	Validation Loss: 0.530637
epoch:  14
Epoch 14, Batch 1 loss: 0.345340, Time 0.4s
Epoch 14, Batch 51 loss: 0.268206, Time 25.1s
Epoch 14, Batch 101 loss: 0.271234, Time 25.2s
Epoch: 14 	Training Loss: 0.270977 	Validation Loss: 0.425268
Validation loss decreased (0.471793 --> 0.425268). Saving model...
epoch:  15
Epoch 15, Batch 1 loss: 0.278078, Time 0.5s
Epoch 15, Batch 51 loss: 0.249798, Time 24.7s
Epoch 15, Batch 101 loss: 0.253127, Time 25.3s
Epoch: 15 	Training Loss: 0.251754 	Validation Loss: 0.411046
Validation loss decreased (0.425268 --> 0.411046). Saving model...
epoch:  16
Epoch 16, Batch 1 loss: 0.240055, Time 0.4s
Epoch 16, Batch 51 loss: 0.232082, Time 24.8s
Epoch 16, Batch 101 loss: 0.239671, Time 25.4s
Epoch: 16 	Training Loss: 0.239702 	Validation Loss: 0.430694
epoch:  17
Epoch 17, Batch 1 loss: 0.273103, Time 0.4s
Epoch 17, Batch 51 loss: 0.241661, Time 25.8s
Epoch 17, Batch 101 loss: 0.232067, Time 24.7s
Epoch: 17 	Training Loss: 0.235316 	Validation Loss: 0.430574
epoch:  18
Epoch 18, Batch 1 loss: 0.128148, Time 0.5s
Epoch 18, Batch 51 loss: 0.210231, Time 25.2s
Epoch 18, Batch 101 loss: 0.212576, Time 25.0s
Epoch: 18 	Training Loss: 0.214065 	Validation Loss: 0.426515
epoch:  19
Epoch 19, Batch 1 loss: 0.271887, Time 0.6s
Epoch 19, Batch 51 loss: 0.216252, Time 25.2s
Epoch 19, Batch 101 loss: 0.210989, Time 24.9s
Epoch: 19 	Training Loss: 0.211181 	Validation Loss: 0.411902
epoch:  20
Epoch 20, Batch 1 loss: 0.186279, Time 0.4s
Epoch 20, Batch 51 loss: 0.196503, Time 25.4s
Epoch 20, Batch 101 loss: 0.196423, Time 25.7s
Epoch: 20 	Training Loss: 0.197240 	Validation Loss: 0.377871
Validation loss decreased (0.411046 --> 0.377871). Saving model...
epoch:  21
Epoch 21, Batch 1 loss: 0.250837, Time 0.6s
Epoch 21, Batch 51 loss: 0.189814, Time 25.1s
Epoch 21, Batch 101 loss: 0.189168, Time 26.0s
Epoch: 21 	Training Loss: 0.190371 	Validation Loss: 0.373244
Validation loss decreased (0.377871 --> 0.373244). Saving model...
epoch:  22
Epoch 22, Batch 1 loss: 0.197086, Time 0.4s
Epoch 22, Batch 51 loss: 0.176674, Time 25.2s
Epoch 22, Batch 101 loss: 0.178441, Time 24.9s
Epoch: 22 	Training Loss: 0.178522 	Validation Loss: 0.513969
epoch:  23
Epoch 23, Batch 1 loss: 0.124668, Time 0.4s
Epoch 23, Batch 51 loss: 0.181949, Time 25.1s
Epoch 23, Batch 101 loss: 0.177033, Time 25.6s
Epoch: 23 	Training Loss: 0.176782 	Validation Loss: 0.389646
epoch:  24
Epoch 24, Batch 1 loss: 0.134444, Time 0.5s
Epoch 24, Batch 51 loss: 0.173774, Time 24.2s
Epoch 24, Batch 101 loss: 0.170046, Time 26.3s
Epoch: 24 	Training Loss: 0.169887 	Validation Loss: 0.365273
Validation loss decreased (0.373244 --> 0.365273). Saving model...
epoch:  25
Epoch 25, Batch 1 loss: 0.145719, Time 0.4s
Epoch 25, Batch 51 loss: 0.159971, Time 26.0s
Epoch 25, Batch 101 loss: 0.158824, Time 24.6s
Epoch: 25 	Training Loss: 0.159145 	Validation Loss: 0.354596
Validation loss decreased (0.365273 --> 0.354596). Saving model...
epoch:  26
Epoch 26, Batch 1 loss: 0.126652, Time 0.6s
Epoch 26, Batch 51 loss: 0.151411, Time 25.2s
Epoch 26, Batch 101 loss: 0.150616, Time 25.4s
Epoch: 26 	Training Loss: 0.150865 	Validation Loss: 0.351191
Validation loss decreased (0.354596 --> 0.351191). Saving model...
epoch:  27
Epoch 27, Batch 1 loss: 0.219923, Time 0.6s
Epoch 27, Batch 51 loss: 0.144651, Time 24.9s
Epoch 27, Batch 101 loss: 0.147720, Time 25.2s
Epoch: 27 	Training Loss: 0.147978 	Validation Loss: 0.391577
epoch:  28
Epoch 28, Batch 1 loss: 0.140921, Time 0.5s
Epoch 28, Batch 51 loss: 0.136817, Time 25.0s
Epoch 28, Batch 101 loss: 0.136764, Time 25.3s
Epoch: 28 	Training Loss: 0.137609 	Validation Loss: 0.392199
epoch:  29
Epoch 29, Batch 1 loss: 0.151515, Time 0.4s
Epoch 29, Batch 51 loss: 0.138091, Time 25.6s
Epoch 29, Batch 101 loss: 0.138323, Time 25.3s
Epoch: 29 	Training Loss: 0.138460 	Validation Loss: 0.405873
epoch:  30
Epoch 30, Batch 1 loss: 0.197653, Time 0.5s
Epoch 30, Batch 51 loss: 0.136086, Time 25.1s
Epoch 30, Batch 101 loss: 0.135010, Time 25.3s
Epoch: 30 	Training Loss: 0.135170 	Validation Loss: 0.363233
epoch:  31
Epoch 31, Batch 1 loss: 0.103406, Time 0.6s
Epoch 31, Batch 51 loss: 0.120741, Time 24.2s
Epoch 31, Batch 101 loss: 0.128354, Time 25.8s
Epoch: 31 	Training Loss: 0.128375 	Validation Loss: 0.354487
epoch:  32
Epoch 32, Batch 1 loss: 0.084214, Time 0.4s
Epoch 32, Batch 51 loss: 0.123045, Time 25.2s
Epoch 32, Batch 101 loss: 0.123554, Time 25.2s
Epoch: 32 	Training Loss: 0.123848 	Validation Loss: 0.339628
Validation loss decreased (0.351191 --> 0.339628). Saving model...
epoch:  33
Epoch 33, Batch 1 loss: 0.089548, Time 0.4s
Epoch 33, Batch 51 loss: 0.116513, Time 25.5s
Epoch 33, Batch 101 loss: 0.118795, Time 24.7s
Epoch: 33 	Training Loss: 0.119128 	Validation Loss: 0.351184
epoch:  34
Epoch 34, Batch 1 loss: 0.119213, Time 0.5s
Epoch 34, Batch 51 loss: 0.112934, Time 24.9s
Epoch 34, Batch 101 loss: 0.112363, Time 26.1s
Epoch: 34 	Training Loss: 0.111802 	Validation Loss: 0.379302
epoch:  35
Epoch 35, Batch 1 loss: 0.095302, Time 0.5s
Epoch 35, Batch 51 loss: 0.102818, Time 25.7s
Epoch 35, Batch 101 loss: 0.109335, Time 25.5s
Epoch: 35 	Training Loss: 0.110876 	Validation Loss: 0.374471
epoch:  36
Epoch 36, Batch 1 loss: 0.129652, Time 0.6s
Epoch 36, Batch 51 loss: 0.103898, Time 25.9s
Epoch 36, Batch 101 loss: 0.105144, Time 24.3s
Epoch: 36 	Training Loss: 0.105663 	Validation Loss: 0.356041
epoch:  37
Epoch 37, Batch 1 loss: 0.118342, Time 0.4s
Epoch 37, Batch 51 loss: 0.101755, Time 25.1s
Epoch 37, Batch 101 loss: 0.102534, Time 26.2s
Epoch: 37 	Training Loss: 0.102784 	Validation Loss: 0.378830
epoch:  38
Epoch 38, Batch 1 loss: 0.056835, Time 0.4s
Epoch 38, Batch 51 loss: 0.098762, Time 25.0s
Epoch 38, Batch 101 loss: 0.099966, Time 25.4s
Epoch: 38 	Training Loss: 0.100279 	Validation Loss: 0.405189
epoch:  39
Epoch 39, Batch 1 loss: 0.082031, Time 0.5s
Epoch 39, Batch 51 loss: 0.100164, Time 25.0s
Epoch 39, Batch 101 loss: 0.100052, Time 25.2s
Epoch: 39 	Training Loss: 0.101462 	Validation Loss: 0.347741
epoch:  40
Epoch 40, Batch 1 loss: 0.065794, Time 0.5s
Epoch 40, Batch 51 loss: 0.091151, Time 25.0s
Epoch 40, Batch 101 loss: 0.095560, Time 25.2s
Epoch: 40 	Training Loss: 0.095054 	Validation Loss: 0.345115
epoch:  41
Epoch 41, Batch 1 loss: 0.083453, Time 0.4s
Epoch 41, Batch 51 loss: 0.093887, Time 24.9s
Epoch 41, Batch 101 loss: 0.091643, Time 24.9s
Epoch: 41 	Training Loss: 0.091954 	Validation Loss: 0.345911
epoch:  42
Epoch 42, Batch 1 loss: 0.074193, Time 0.4s
Epoch 42, Batch 51 loss: 0.087598, Time 25.0s
Epoch 42, Batch 101 loss: 0.089047, Time 24.7s
Epoch: 42 	Training Loss: 0.090636 	Validation Loss: 0.381242
epoch:  43
Epoch 43, Batch 1 loss: 0.077909, Time 0.4s
Epoch 43, Batch 51 loss: 0.084977, Time 24.8s
Epoch 43, Batch 101 loss: 0.087854, Time 25.7s
Epoch: 43 	Training Loss: 0.089633 	Validation Loss: 0.344814
epoch:  44
Epoch 44, Batch 1 loss: 0.074959, Time 0.4s
Epoch 44, Batch 51 loss: 0.085010, Time 25.0s
Epoch 44, Batch 101 loss: 0.082192, Time 25.7s
Epoch: 44 	Training Loss: 0.083374 	Validation Loss: 0.355176
epoch:  45
Epoch 45, Batch 1 loss: 0.102382, Time 0.4s
Epoch 45, Batch 51 loss: 0.087793, Time 24.4s
Epoch 45, Batch 101 loss: 0.084689, Time 26.3s
Epoch: 45 	Training Loss: 0.084355 	Validation Loss: 0.339768
epoch:  46
Epoch 46, Batch 1 loss: 0.078985, Time 0.5s
Epoch 46, Batch 51 loss: 0.082793, Time 25.4s
Epoch 46, Batch 101 loss: 0.084332, Time 25.1s
Epoch: 46 	Training Loss: 0.086396 	Validation Loss: 0.346830
epoch:  47
Epoch 47, Batch 1 loss: 0.150860, Time 0.5s
Epoch 47, Batch 51 loss: 0.074195, Time 25.8s
Epoch 47, Batch 101 loss: 0.078007, Time 24.8s
Epoch: 47 	Training Loss: 0.078833 	Validation Loss: 0.424780
epoch:  48
Epoch 48, Batch 1 loss: 0.082006, Time 0.4s
Epoch 48, Batch 51 loss: 0.078645, Time 24.7s
Epoch 48, Batch 101 loss: 0.080207, Time 25.5s
Epoch: 48 	Training Loss: 0.079806 	Validation Loss: 0.354507
epoch:  49
Epoch 49, Batch 1 loss: 0.036421, Time 0.6s
Epoch 49, Batch 51 loss: 0.080799, Time 25.1s
Epoch 49, Batch 101 loss: 0.079319, Time 25.4s
Epoch: 49 	Training Loss: 0.079669 	Validation Loss: 0.331233
Validation loss decreased (0.339628 --> 0.331233). Saving model...
epoch:  50
Epoch 50, Batch 1 loss: 0.042631, Time 0.4s
Epoch 50, Batch 51 loss: 0.075716, Time 24.6s
Epoch 50, Batch 101 loss: 0.071440, Time 25.6s
Epoch: 50 	Training Loss: 0.071575 	Validation Loss: 0.384664
epoch:  51
Epoch 51, Batch 1 loss: 0.091951, Time 0.5s
Epoch 51, Batch 51 loss: 0.070022, Time 24.9s
Epoch 51, Batch 101 loss: 0.074242, Time 25.5s
Epoch: 51 	Training Loss: 0.075732 	Validation Loss: 0.347575
epoch:  52
Epoch 52, Batch 1 loss: 0.066933, Time 0.5s
Epoch 52, Batch 51 loss: 0.075732, Time 25.3s
Epoch 52, Batch 101 loss: 0.072239, Time 25.5s
Epoch: 52 	Training Loss: 0.072320 	Validation Loss: 0.340223
epoch:  53
Epoch 53, Batch 1 loss: 0.037669, Time 0.5s
Epoch 53, Batch 51 loss: 0.069192, Time 25.7s
Epoch 53, Batch 101 loss: 0.069723, Time 24.8s
Epoch: 53 	Training Loss: 0.070047 	Validation Loss: 0.363816
epoch:  54
Epoch 54, Batch 1 loss: 0.043606, Time 0.5s
Epoch 54, Batch 51 loss: 0.060620, Time 25.1s
Epoch 54, Batch 101 loss: 0.065371, Time 25.3s
Epoch: 54 	Training Loss: 0.065111 	Validation Loss: 0.343158
epoch:  55
Epoch 55, Batch 1 loss: 0.042623, Time 0.5s
Epoch 55, Batch 51 loss: 0.064785, Time 24.7s
Epoch 55, Batch 101 loss: 0.064086, Time 26.1s
Epoch: 55 	Training Loss: 0.064635 	Validation Loss: 0.453081
epoch:  56
Epoch 56, Batch 1 loss: 0.052422, Time 0.4s
Epoch 56, Batch 51 loss: 0.065945, Time 25.5s
Epoch 56, Batch 101 loss: 0.066463, Time 25.1s
Epoch: 56 	Training Loss: 0.067084 	Validation Loss: 0.352312
epoch:  57
Epoch 57, Batch 1 loss: 0.122471, Time 0.4s
Epoch 57, Batch 51 loss: 0.059469, Time 25.8s
Epoch 57, Batch 101 loss: 0.061521, Time 24.3s
Epoch: 57 	Training Loss: 0.061720 	Validation Loss: 0.347308
epoch:  58
Epoch 58, Batch 1 loss: 0.048583, Time 0.7s
Epoch 58, Batch 51 loss: 0.064577, Time 24.9s
Epoch 58, Batch 101 loss: 0.059541, Time 25.3s
Epoch: 58 	Training Loss: 0.060803 	Validation Loss: 0.422028
epoch:  59
Epoch 59, Batch 1 loss: 0.070538, Time 0.6s
Epoch 59, Batch 51 loss: 0.056188, Time 24.7s
Epoch 59, Batch 101 loss: 0.060891, Time 25.8s
Epoch: 59 	Training Loss: 0.061980 	Validation Loss: 0.346512
epoch:  60
Epoch 60, Batch 1 loss: 0.054016, Time 0.4s
Epoch 60, Batch 51 loss: 0.062039, Time 25.6s
Epoch 60, Batch 101 loss: 0.058448, Time 25.2s
Epoch: 60 	Training Loss: 0.058637 	Validation Loss: 0.392330
epoch:  61
Epoch 61, Batch 1 loss: 0.042787, Time 0.6s
Epoch 61, Batch 51 loss: 0.057097, Time 25.7s
Epoch 61, Batch 101 loss: 0.057717, Time 24.9s
Epoch: 61 	Training Loss: 0.057697 	Validation Loss: 0.398771
epoch:  62
Epoch 62, Batch 1 loss: 0.054457, Time 0.6s
Epoch 62, Batch 51 loss: 0.061715, Time 25.9s
Epoch 62, Batch 101 loss: 0.061740, Time 25.1s
Epoch: 62 	Training Loss: 0.061177 	Validation Loss: 0.351746
epoch:  63
Epoch 63, Batch 1 loss: 0.045541, Time 0.6s
Epoch 63, Batch 51 loss: 0.059308, Time 25.6s
Epoch 63, Batch 101 loss: 0.057129, Time 25.3s
Epoch: 63 	Training Loss: 0.057316 	Validation Loss: 0.351299
epoch:  64
Epoch 64, Batch 1 loss: 0.037933, Time 0.5s
Epoch 64, Batch 51 loss: 0.051969, Time 25.9s
Epoch 64, Batch 101 loss: 0.053324, Time 26.2s
Epoch: 64 	Training Loss: 0.053229 	Validation Loss: 0.340427
epoch:  65
Epoch 65, Batch 1 loss: 0.056278, Time 0.6s
Epoch 65, Batch 51 loss: 0.055332, Time 24.8s
Epoch 65, Batch 101 loss: 0.053798, Time 24.8s
Epoch: 65 	Training Loss: 0.054555 	Validation Loss: 0.405584
epoch:  66
Epoch 66, Batch 1 loss: 0.032167, Time 0.5s
Epoch 66, Batch 51 loss: 0.048513, Time 24.8s
Epoch 66, Batch 101 loss: 0.049304, Time 25.3s
Epoch: 66 	Training Loss: 0.050916 	Validation Loss: 0.362953
epoch:  67
Epoch 67, Batch 1 loss: 0.028522, Time 0.5s
Epoch 67, Batch 51 loss: 0.053998, Time 25.7s
Epoch 67, Batch 101 loss: 0.051813, Time 25.4s
Epoch: 67 	Training Loss: 0.052084 	Validation Loss: 0.351467
epoch:  68
Epoch 68, Batch 1 loss: 0.020340, Time 0.5s
Epoch 68, Batch 51 loss: 0.050778, Time 25.2s
Epoch 68, Batch 101 loss: 0.053407, Time 25.3s
Epoch: 68 	Training Loss: 0.053268 	Validation Loss: 0.383307
epoch:  69
Epoch 69, Batch 1 loss: 0.042541, Time 0.4s
Epoch 69, Batch 51 loss: 0.052189, Time 24.7s
Epoch 69, Batch 101 loss: 0.054031, Time 26.6s
Epoch: 69 	Training Loss: 0.055810 	Validation Loss: 0.366181
epoch:  70
Epoch 70, Batch 1 loss: 0.033168, Time 0.6s
Epoch 70, Batch 51 loss: 0.051870, Time 26.3s
Epoch 70, Batch 101 loss: 0.049418, Time 24.4s
Epoch: 70 	Training Loss: 0.048803 	Validation Loss: 0.418302
epoch:  71
Epoch 71, Batch 1 loss: 0.106735, Time 0.5s
Epoch 71, Batch 51 loss: 0.046691, Time 25.5s
Epoch 71, Batch 101 loss: 0.045530, Time 25.4s
Epoch: 71 	Training Loss: 0.046579 	Validation Loss: 0.360238
epoch:  72
Epoch 72, Batch 1 loss: 0.038862, Time 0.5s
Epoch 72, Batch 51 loss: 0.051087, Time 25.5s
Epoch 72, Batch 101 loss: 0.051444, Time 25.6s
Epoch: 72 	Training Loss: 0.052049 	Validation Loss: 0.401590
epoch:  73
Epoch 73, Batch 1 loss: 0.039533, Time 0.5s
Epoch 73, Batch 51 loss: 0.044028, Time 24.9s
Epoch 73, Batch 101 loss: 0.045649, Time 25.3s
Epoch: 73 	Training Loss: 0.046000 	Validation Loss: 0.366152
epoch:  74
Epoch 74, Batch 1 loss: 0.033560, Time 0.6s
Epoch 74, Batch 51 loss: 0.044267, Time 25.3s
Epoch 74, Batch 101 loss: 0.047366, Time 25.2s
Epoch: 74 	Training Loss: 0.048915 	Validation Loss: 0.360359
epoch:  75
Epoch 75, Batch 1 loss: 0.046040, Time 0.5s
Epoch 75, Batch 51 loss: 0.046247, Time 25.2s
Epoch 75, Batch 101 loss: 0.046658, Time 25.0s
Epoch: 75 	Training Loss: 0.047214 	Validation Loss: 0.349428
epoch:  76
Epoch 76, Batch 1 loss: 0.025365, Time 0.5s
Epoch 76, Batch 51 loss: 0.042301, Time 25.4s
Epoch 76, Batch 101 loss: 0.044077, Time 24.9s
Epoch: 76 	Training Loss: 0.044131 	Validation Loss: 0.346227
epoch:  77
Epoch 77, Batch 1 loss: 0.052359, Time 0.4s
Epoch 77, Batch 51 loss: 0.045003, Time 25.3s
Epoch 77, Batch 101 loss: 0.043900, Time 25.3s
Epoch: 77 	Training Loss: 0.044578 	Validation Loss: 0.462889
epoch:  78
Epoch 78, Batch 1 loss: 0.046367, Time 0.4s
Epoch 78, Batch 51 loss: 0.038299, Time 25.2s
Epoch 78, Batch 101 loss: 0.041043, Time 25.2s
Epoch: 78 	Training Loss: 0.041298 	Validation Loss: 0.353780
epoch:  79
Epoch 79, Batch 1 loss: 0.070339, Time 0.5s
Epoch 79, Batch 51 loss: 0.041809, Time 24.3s
Epoch 79, Batch 101 loss: 0.043103, Time 26.0s
Epoch: 79 	Training Loss: 0.043193 	Validation Loss: 0.369379
epoch:  80
Epoch 80, Batch 1 loss: 0.029479, Time 0.6s
Epoch 80, Batch 51 loss: 0.041412, Time 26.0s
Epoch 80, Batch 101 loss: 0.042625, Time 25.0s
Epoch: 80 	Training Loss: 0.042539 	Validation Loss: 0.448928
epoch:  81
Epoch 81, Batch 1 loss: 0.067549, Time 0.7s
Epoch 81, Batch 51 loss: 0.038724, Time 25.3s
Epoch 81, Batch 101 loss: 0.040401, Time 24.7s
Epoch: 81 	Training Loss: 0.041445 	Validation Loss: 0.345074
epoch:  82
Epoch 82, Batch 1 loss: 0.036762, Time 0.6s
Epoch 82, Batch 51 loss: 0.038235, Time 25.4s
Epoch 82, Batch 101 loss: 0.039374, Time 25.0s
Epoch: 82 	Training Loss: 0.039960 	Validation Loss: 0.377355
epoch:  83
Epoch 83, Batch 1 loss: 0.026151, Time 0.5s
Epoch 83, Batch 51 loss: 0.039983, Time 26.1s
Epoch 83, Batch 101 loss: 0.039712, Time 24.7s
Epoch: 83 	Training Loss: 0.040060 	Validation Loss: 0.415322
epoch:  84
Epoch 84, Batch 1 loss: 0.032830, Time 0.4s
Epoch 84, Batch 51 loss: 0.036347, Time 25.1s
Epoch 84, Batch 101 loss: 0.038416, Time 25.3s
Epoch: 84 	Training Loss: 0.040157 	Validation Loss: 0.381382
epoch:  85
Epoch 85, Batch 1 loss: 0.029906, Time 0.4s
Epoch 85, Batch 51 loss: 0.042046, Time 25.1s
Epoch 85, Batch 101 loss: 0.039778, Time 25.1s
Epoch: 85 	Training Loss: 0.040984 	Validation Loss: 0.382430
epoch:  86
Epoch 86, Batch 1 loss: 0.050407, Time 0.4s
Epoch 86, Batch 51 loss: 0.043997, Time 24.9s
Epoch 86, Batch 101 loss: 0.040750, Time 25.6s
Epoch: 86 	Training Loss: 0.041334 	Validation Loss: 0.411862
epoch:  87
Epoch 87, Batch 1 loss: 0.073516, Time 0.4s
Epoch 87, Batch 51 loss: 0.037790, Time 25.6s
Epoch 87, Batch 101 loss: 0.038679, Time 25.1s
Epoch: 87 	Training Loss: 0.038652 	Validation Loss: 0.358722
epoch:  88
Epoch 88, Batch 1 loss: 0.044274, Time 0.5s
Epoch 88, Batch 51 loss: 0.038915, Time 25.7s
Epoch 88, Batch 101 loss: 0.038089, Time 24.6s
Epoch: 88 	Training Loss: 0.037824 	Validation Loss: 0.360012
epoch:  89
Epoch 89, Batch 1 loss: 0.063638, Time 0.4s
Epoch 89, Batch 51 loss: 0.037728, Time 25.2s
Epoch 89, Batch 101 loss: 0.038886, Time 25.7s
Epoch: 89 	Training Loss: 0.038732 	Validation Loss: 0.366920
epoch:  90
Epoch 90, Batch 1 loss: 0.025014, Time 0.5s
Epoch 90, Batch 51 loss: 0.035220, Time 25.9s
Epoch 90, Batch 101 loss: 0.036024, Time 25.1s
Epoch: 90 	Training Loss: 0.036326 	Validation Loss: 0.466331
epoch:  91
Epoch 91, Batch 1 loss: 0.083383, Time 0.4s
Epoch 91, Batch 51 loss: 0.039776, Time 25.8s
Epoch 91, Batch 101 loss: 0.038157, Time 24.9s
Epoch: 91 	Training Loss: 0.039710 	Validation Loss: 0.360704
epoch:  92
Epoch 92, Batch 1 loss: 0.020204, Time 0.5s
Epoch 92, Batch 51 loss: 0.031343, Time 25.5s
Epoch 92, Batch 101 loss: 0.032481, Time 26.0s
Epoch: 92 	Training Loss: 0.033530 	Validation Loss: 0.367288
epoch:  93
Epoch 93, Batch 1 loss: 0.042085, Time 0.4s
Epoch 93, Batch 51 loss: 0.035576, Time 26.5s
Epoch 93, Batch 101 loss: 0.034793, Time 25.6s
Epoch: 93 	Training Loss: 0.036375 	Validation Loss: 0.385314
epoch:  94
Epoch 94, Batch 1 loss: 0.053920, Time 0.5s
Epoch 94, Batch 51 loss: 0.033679, Time 25.6s
Epoch 94, Batch 101 loss: 0.033206, Time 25.5s
Epoch: 94 	Training Loss: 0.033605 	Validation Loss: 0.378112
epoch:  95
Epoch 95, Batch 1 loss: 0.024113, Time 0.5s
Epoch 95, Batch 51 loss: 0.034838, Time 25.9s
Epoch 95, Batch 101 loss: 0.034439, Time 24.6s
Epoch: 95 	Training Loss: 0.034378 	Validation Loss: 0.392435
epoch:  96
Epoch 96, Batch 1 loss: 0.030103, Time 0.6s
Epoch 96, Batch 51 loss: 0.031278, Time 25.5s
Epoch 96, Batch 101 loss: 0.032679, Time 25.1s
Epoch: 96 	Training Loss: 0.033091 	Validation Loss: 0.365148
epoch:  97
Epoch 97, Batch 1 loss: 0.030165, Time 0.5s
Epoch 97, Batch 51 loss: 0.031271, Time 25.1s
Epoch 97, Batch 101 loss: 0.029983, Time 25.7s
Epoch: 97 	Training Loss: 0.030508 	Validation Loss: 0.363649
epoch:  98
Epoch 98, Batch 1 loss: 0.030282, Time 0.5s
Epoch 98, Batch 51 loss: 0.029386, Time 25.4s
Epoch 98, Batch 101 loss: 0.031565, Time 26.4s
Epoch: 98 	Training Loss: 0.031649 	Validation Loss: 0.397585
epoch:  99
Epoch 99, Batch 1 loss: 0.022687, Time 0.6s
Epoch 99, Batch 51 loss: 0.029038, Time 24.8s
Epoch 99, Batch 101 loss: 0.031257, Time 25.4s
Epoch: 99 	Training Loss: 0.031511 	Validation Loss: 0.503940
epoch:  100
Epoch 100, Batch 1 loss: 0.023547, Time 0.5s
Epoch 100, Batch 51 loss: 0.027361, Time 25.0s
Epoch 100, Batch 101 loss: 0.027626, Time 25.9s
Epoch: 100 	Training Loss: 0.028078 	Validation Loss: 0.485079
Out[248]:
<All keys matched successfully>

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [252]:
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
# below accuracy when we USE nn.init.kaiming_normal_
# Test Loss: 0.409725
# Test Accuracy: 88% (739/836)
## below accuracy when we DO NOT USE nn.init.kaiming_normal_
#Test Loss: 0.406121
#Test Accuracy: 88% (736/836)
Test Loss: 0.406121


Test Accuracy: 88% (736/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [189]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
#
from PIL import Image
from torch.autograd import Variable
#
# list of class names by index, i.e. a name can be accessed like class_names[0]
data_transfer = loaders_transfer
class_names = [item[4:].replace("_", " ") for item in data_transfer['train'].dataset.classes]
#
def show_image_from_path(img_path, title = None):
    img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
    plt.imshow(img)
    plt.gca().set_xticks([])
    plt.gca().set_yticks([])
    if title is not None:
        plt.gca().set_title(title)
    plt.show()
#
def predict_breed_transfer(img_path, model_transfer):
    # Handle image transforms    
    transform = transforms.Compose([transforms.Resize(size=250),
                                    transforms.CenterCrop(224),
                                    transforms.ToTensor(),
                                    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                         std=[0.229, 0.224, 0.225])])
    #
    # Load image and run through transform      
    image = transform(Image.open(img_path))
    # Add dimension to tensor for number of images
    image = image.unsqueeze(0)
    # Prediction placeholder
    # Depending on whether cuda is being used, make sure the passed tensor
    # is being moved between the cpu and GPU pre/post calculation.
    if use_cuda:
       image = Variable(image).cuda()
    else:
       image = Variable(image)
    #
    prediction = model_transfer.forward(image)
    #
    if use_cuda:
       prediction = prediction.to("cpu")
    #
    # To access the index of the highest predicted class value, we access
    # the data of the prediction and find the index of it's highest propbablity
    #
    #return class_names[prediction.data.numpy().argmax()]
    output     = torch.argmax(prediction).to("cpu").item()
    probs      = F.softmax(prediction, dim = 1).to("cpu").data.numpy()
    #
    return output, probs[0]
#
test_image = dog_files_short[0]
label_index, probs = predict_breed_transfer(test_image, model_transfer)
show_image_from_path(test_image, title = class_names[label_index])
#
print("label_index: ", label_index, ", dog breed: ", class_names[label_index])
print("Prediction probs: ", probs)
#
label_index:  0 , dog breed:  Affenpinscher
Prediction probs:  [9.9255651e-01 5.7739229e-04 3.0953897e-06 1.7222081e-06 7.6879987e-09
 2.8205649e-08 8.3416896e-10 3.4622136e-07 4.6790902e-08 2.4555979e-08
 7.0105708e-09 2.0518735e-08 9.0270996e-06 1.4233837e-07 3.3804890e-09
 1.1905156e-08 2.5538624e-05 1.0426471e-08 1.4957809e-08 1.6703765e-09
 8.8561347e-07 2.4343002e-08 1.9039087e-08 2.5983866e-08 4.7141718e-11
 5.6498415e-05 6.9037647e-09 1.5851288e-09 3.1422601e-07 2.4973801e-07
 5.1325785e-08 2.5796746e-07 1.7522811e-04 2.1155127e-07 4.4439761e-07
 7.2901649e-04 1.9149912e-08 7.3404990e-06 2.8358688e-08 1.3871329e-09
 5.4013009e-07 3.7462348e-03 3.2514498e-07 3.1242255e-08 1.1412971e-08
 1.4519399e-06 1.1413994e-08 1.7680019e-07 6.0883263e-04 1.0875886e-08
 3.0284136e-07 1.7319645e-09 5.2457153e-07 4.7321760e-09 6.7411003e-07
 6.0786606e-06 8.0243062e-08 1.5319148e-07 1.7333400e-08 2.9295313e-07
 5.6237290e-08 1.1896916e-08 3.3351029e-08 1.8402404e-06 1.1890422e-09
 1.3475362e-07 5.7072231e-07 8.5333284e-08 2.0507635e-07 2.0232203e-08
 5.1107843e-08 4.0509809e-09 8.0397371e-07 7.1289796e-06 1.7854407e-05
 1.6938551e-09 3.3351651e-07 1.8744439e-09 2.7901605e-09 5.0480415e-09
 1.3622799e-08 4.4759316e-05 1.1870329e-08 3.5952961e-08 1.0250425e-06
 3.3524948e-08 2.2778936e-08 4.4023991e-06 2.2798943e-07 3.0976604e-08
 8.6457618e-07 6.2906416e-08 7.1165896e-06 1.1208182e-08 8.7709973e-09
 8.0159799e-09 1.9552459e-07 1.7231864e-09 4.7100807e-06 7.5759497e-05
 4.3468581e-06 5.1688296e-08 1.7588169e-08 1.5596700e-07 7.3855865e-08
 2.9209100e-06 4.3767062e-07 2.6870010e-08 2.9153826e-08 7.6245438e-10
 1.2878823e-07 1.3784958e-08 2.0288352e-08 3.6117603e-10 2.3488386e-05
 4.4704432e-08 2.3226343e-05 2.4198328e-09 9.1535368e-10 3.0300748e-07
 1.0314197e-09 2.7143210e-09 1.0287894e-06 1.3275533e-07 3.4267450e-06
 9.5445507e-10 1.0235739e-03 2.2821338e-08 7.8494156e-07 1.2434133e-07
 7.5744683e-05 7.1271883e-05 8.9550609e-05]

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [231]:
#
def get_random_path_given_breed(breed):
    breed_files = [{"breed": path.split(".")[1].split("\\")[0].replace("_", " "), "path" : path} for path in dog_files]
    #
    breed_files_df = pd.DataFrame(breed_files)
    #
    df = breed_files_df[breed_files_df["breed"] == breed].copy()
    df = df.sample(n=2, replace = False)
    path1 = df["path"].values[0]
    path2 = df["path"].values[1]
    #
    return path1, path2
#
In [237]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
#
def show_images_with_info(img_path, title_picture, title_pie, resemblance_breeds, resemblance_probs):
    # Read the image
    breed      = resemblance_breeds[0]
    confidence = resemblance_probs[0]
    print("With confidence ", np.round(confidence * 100.0, 1), " dog breed is ", breed)
    #
    path1, path2 = get_random_path_given_breed(breed)
    #
    img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)  
    # Show the image
    fig, ax = plt.subplots(1,2,figsize=(10,4))  
    #
    ax[0].imshow(img)
    ax[0].set_xticks([])
    ax[0].set_yticks([])   
    ax[0].set_title(title_picture)
    #
    if resemblance_breeds[0] == "Nobody":
       resemblance_probs = [0.0]
    #
    wedges, texts, autotexts = ax[1].pie(resemblance_probs, 
                                             autopct='%1.1f%%', wedgeprops = {'linewidth': 0})
    ax[1].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
    ax[1].legend(wedges, resemblance_breeds, title="Likely breeds",
                     loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))    
    ax[1].set_title(title_pie)
    plt.show()
    #
    if resemblance_breeds[0] != "Nobody":
       fig, ax = plt.subplots(1,2,figsize=(10,4))  
       #
       img_path = path1
       print("path1: ", path1)
       img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
       ax[0].imshow(img)
       ax[0].set_xticks([])
       ax[0].set_yticks([])
       ax[0].set_title("First example of " + breed)
       #
       img_path = path2
       print("path2: ", path2)
       img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
       ax[1].imshow(img)
       ax[1].set_xticks([])
       ax[1].set_yticks([])
       ax[1].set_title("Second example of " + breed)
       #
       plt.show()    
#    
def probability_processing(probs, n = 3):
    #
    threshold = 1/len(class_names) # equal probabilities 
    #
    df = pd.DataFrame({"breed": class_names, "confidence": probs})
    df = df.sort_values(by = "confidence", ascending = False).head(n)
    #
    # Let's discard unlikely breeds
    df = df[df["confidence"] > threshold].copy()
    #
    resemblance_breeds = list(df["breed"     ].values)
    resemblance_probs  = list(df["confidence"].values)
    #    
    if len(df) > 0:
       if   (len(df) > 1) or ((len(df) == 1) and (resemblance_probs[0] < 0.99)):
            resemblance_breeds = resemblance_breeds + ["Other"]
            resemblance_probs  = resemblance_probs  + [1 - sum(resemblance_probs)]
       elif (len(df) == 1) and (resemblance_probs[0] >= 0.99):
            # If no other breed is predicted with at least 1% let's round up the confidence to 100% 
            resemblance_probs = [1.0]
    else: #uniformly classified - equal probabilities 
          resemblance_probs  = [threshold]
          resemblance_breeds = ["Nobody"]
    # 
    #resemblance_probs  = [threshold]  # I use this line for testing
    #resemblance_breeds = ["Nobody" ]  # I use this line for testing
    return resemblance_breeds, resemblance_probs
#
def run_app(img_path, model_transfer):
    ## handle cases for a human face, dog, and neither 
    # Check if a dog is detected
    dog_detected = dog_detector(img_path)
    # Check if a human is detected
    threshold = 0.98
    human_detected = human_detector_AD(img_path, 0) >= threshold
    # Get the predicted breed(s)
    pred, probs = predict_breed_transfer(img_path, model_transfer)
    # Replace low probabilities classes with "other"
    resemblance_breeds, resemblance_probs = probability_processing(probs)
    # Decide on titles and such
    confidence = resemblance_probs[0]
    confidence = np.round(confidence*100, 1)
    #
    if dog_detected:
        title = f"Dog looks like {resemblance_breeds[0]}!" + "\nConfidence is " + str(confidence) + "%"
        if len(resemblance_breeds) == 1:
           pie_title = "A purebred!"
        else:
           pie_title = "Such a mix we've got here..."
    elif human_detected:
        title     = f"Person looks like a {resemblance_breeds[0]}!" + "\nConfidence is " + str(confidence) + "%"
        pie_title = "Person looka like those dogs:"               
    else:
        title     = "Error: neither dog or person is detected in the image..."
        pie_title = None
        
    # Show everything
    #
    show_images_with_info(img_path, title, pie_title, resemblance_breeds, resemblance_probs)   

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: (Three possible points for improvement) Output of the dog breed classification is surprisenly good. But it is a bit unclear why some people classified as a certain dog breed with high confidence (>60%).

  • Dataset is unbalance: Norwegian buhund has 26 training examples but Alaskan malamute - 77 examples. We can use upper sampling to make balanced training dataset;
  • We can add one more fully connected layer to model_transfer model and play with different number of neurons in this layer;
  • We can use a different pre-trained model;
  • We can perform stacking of different pre-trained models.
In [238]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

## suggested code, below
import random
sample_human_files = random.sample(list(human_files), 5)
sample_dog_files   = random.sample(list(dog_files),   5)
#
for file in np.hstack((sample_human_files, sample_dog_files)):
    run_app(file, model_transfer)
With confidence  17.0  dog breed is  Lowchen
path1:  dogImages\train\100.Lowchen\Lowchen_06705.jpg
path2:  dogImages\train\100.Lowchen\Lowchen_06675.jpg
With confidence  21.6  dog breed is  Irish wolfhound
path1:  dogImages\train\089.Irish_wolfhound\Irish_wolfhound_06085.jpg
path2:  dogImages\train\089.Irish_wolfhound\Irish_wolfhound_06062.jpg
With confidence  12.7  dog breed is  Norfolk terrier
path1:  dogImages\valid\107.Norfolk_terrier\Norfolk_terrier_07087.jpg
path2:  dogImages\train\107.Norfolk_terrier\Norfolk_terrier_07080.jpg
With confidence  60.8  dog breed is  Lowchen
path1:  dogImages\train\100.Lowchen\Lowchen_06673.jpg
path2:  dogImages\train\100.Lowchen\Lowchen_06692.jpg
With confidence  24.7  dog breed is  Akita
path1:  dogImages\train\004.Akita\Akita_00268.jpg
path2:  dogImages\train\004.Akita\Akita_00285.jpg
With confidence  82.8  dog breed is  American staffordshire terrier
path1:  dogImages\train\008.American_staffordshire_terrier\American_staffordshire_terrier_00612.jpg
path2:  dogImages\test\008.American_staffordshire_terrier\American_staffordshire_terrier_00567.jpg
With confidence  100.0  dog breed is  Briard
path1:  dogImages\train\036.Briard\Briard_02579.jpg
path2:  dogImages\train\036.Briard\Briard_02510.jpg
With confidence  80.5  dog breed is  Pomeranian
path1:  dogImages\valid\123.Pomeranian\Pomeranian_07866.jpg
path2:  dogImages\test\123.Pomeranian\Pomeranian_07861.jpg
With confidence  100.0  dog breed is  Gordon setter
path1:  dogImages\train\077.Gordon_setter\Gordon_setter_05297.jpg
path2:  dogImages\valid\077.Gordon_setter\Gordon_setter_05271.jpg
With confidence  96.3  dog breed is  Glen of imaal terrier
path1:  dogImages\valid\075.Glen_of_imaal_terrier\Glen_of_imaal_terrier_05152.jpg
path2:  dogImages\train\075.Glen_of_imaal_terrier\Glen_of_imaal_terrier_05167.jpg
In [239]:
import os
In [242]:
path = "dogImages/train"
sub_paths = os.listdir(path)
final = []
for sub_path in sub_paths:
    full_path = os.path.join(path, sub_path)
    names = os.listdir(full_path)
    #print("sub path: ", sub_path, ", number of files: ", len(names))
    elem = {"breed": sub_path, "number": len(names)}
    final.append(elem)
final_df = pd.DataFrame(final)
final_df.sort_values(by = "number", inplace = True)
final_df
Out[242]:
breed number
107 108.Norwegian_buhund 26
131 132.Xoloitzcuintli 26
120 121.Plott 28
101 102.Manchester_terrier 29
132 133.Yorkshire_terrier 30
... ... ...
13 014.Basenji 69
56 057.Dalmatian 71
14 015.Basset_hound 73
28 029.Border_collie 74
4 005.Alaskan_malamute 77

133 rows × 2 columns

In [ ]: